Python error handling method

Abnormal capture and handling

What is wrong

In short: It hasn't been run yet, and when the grammar is analyzed, it is found that there is a problem with the grammar, which is an error at this time.

What is abnormal

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 warning

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


How to deal with the exception

The exception handling form is as follows:

try: What you want to do that may be abnormal. except The exception that may occur: What to do after the exception occurs. The exception that may occur 2: The thing to do after the 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:

with open("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 prevent the entire program from crashing

Custom exception and exception throw

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

class MyException(Exception): def __init__(self, parameter): err ='Illegal input parameter {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) return 12/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") # here directly raise the caught exception raise


unit test

What is unit testing

  • Unit testing (English: Unit Testing), also known as module testing, is a testing work for correctness verification of program modules (the smallest unit of software design). The program unit is the smallest testable part of the application. In procedural programming, a unit is a single program, function, process, etc.; for object-oriented programming, the smallest unit is a method, including methods in a base class (superclass), abstract class, or derived class (subclass).

  • In short: is to write a piece of code to verify the correctness of another piece of code in a specific situation

The benefits and "disadvantages" of unit testing

  • Benefits: reduce bugs, improve code quality, and can be refactored with confidence (when future modifications are implemented, the behavior of the code can be guaranteed to be correct)

  • "Disadvantages": take up development time, especially in the initial stage

How to write unit tests in python

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

class MyTest(): 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


v2-02163e8b1a5f25bdcf40e054249f6d53_720w.png


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


v2-fcc1d7bc3069528334bb09d4e056d72d_720w.png


4. Write test code and execute unit test

import unittestfrom unittest import TestCasefrom test import MyTest class TestMyTest(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!


Guess you like

Origin blog.51cto.com/14825302/2543008