Python error handling method

Abnormal capture and handling

What is an error

In short: It hasn't been run yet, and it is found that there is a problem with the grammar during the parsing of the grammar. This time it is an error.

What is an exception

In short: After the code is written, there is no obvious grammatical error (at this time, the editor does not know that there is an error, nor does it know that there is an error during grammar parsing), but when it is run, an error will occur, which is called an exception at this time .

What is a warning

import warnings

def fxn():
 warnings.warn("deprecated", DeprecationWarning)

How to deal with the exception

The exception handling form is as follows:

try:
 Something unusual may happen to you
except exceptions that may occur:
 Things to do after an exception
except the exception that may occur 2:
 Things to do after an exception occurs 2finally:
 The final thing to do

For example, the following code:

try:print(10/0)
except ZeroDivisionError:print("Divisor cannot be 0")

Run again at this time, there will be no exception

In normal development, pre-defined cleanup operations are also used to avoid program crashes due to exceptions. For example, when performing IO operations, you can use:

withopen("myfile.txt")as f:for line in f:print(line, end="")

In this way, once an exception occurs during operation, the program will automatically close the file for you to avoid the entire program from crashing

Custom exception and exception throwing

Although python provides a lot of built-in exception classes, in normal development, for a specific business, you may need to customize exceptions. What should I do at this time?

Customization of exceptions can be achieved by custom inheriting the Exception class

classMyException(Exception):
 def __init__(self, parameter):
 err ='Illegal entry{0}, The denominator cannot be 0'.format(parameter)
 Exception.__init__(self, err)
 self.parameter = parameter

When we encounter a special business situation in our code and need to throw a custom exception to the caller, we can use the raise keyword

from chapter12.my_exception import MyException

def my_fun(x):if x ==0:
 raise MyException(x)return12/x

print(my_fun(-12))

After catching the exception, we can also throw the exception directly. In this case, we can directly use the raise keyword

def my_func():try:print(10/0)
 except ZeroDivisionError:print("Divisor cannot be 0")
 # Throw the caught exception directly here
 raise

unit test

What is unit testing

The benefits and "disadvantages" of unit testing

How to write unit tests in python

1、 Create a new python file and write specific business code

classMyTest():
  def my_add(self, a, b):return a + b

2、 Right-click the class name and select Go TO ==》test, or directly ctrl+shift +t

3、 Fill in the corresponding module name and test class name, click ok, then pycharm will help us automatically create test modules and classes

4、 Write test code and execute unit test

import unittest
from unittest import TestCase
from test import MyTest

classTestMyTest(TestCase):
def test_add(self):
 s=MyTest()
 self.assertEqual(s.my_add(1,5),6)if __name__ =="__main__":
unittest.main()

The above is the detailed content of Python error handling methods. For more information about Python error handling, please pay attention to other related articles on ZaLou.Cn!

Recommended Posts

Python error handling method
Python error handling assert detailed explanation
Python exception handling
Python magic method topic
Python object-oriented magic method
Python3.7 debugging example method
Python function-dictionary get() method
Python defines a function method
Solution to python alignment error
Python TCP packet injection method
Python drawing ring graph method
Python tracking except information method
Python implements gradient descent method
Python common exception handling mechanism
Python right alignment example method
Python method of parameter passing
Python arithmetic sequence calculation method
Method steps to increase python font
Summary of logarithm method in Python
Python implements the steepest descent method
End the method of running python
Error when installing Python module on Ubuntu
A practical guide to Python file handling
Method of installing django module in python
python implements the gradient method python the fastest descent method
The specific method of python instantiation object
Python Romberg method to find integral examples
Example method of reading sql from python
Python example method to open music files
The specific method of python import library
Python replacement pip source method process analysis