How to handle exceptions in Python? Python exception handling

7.3 Exception handling

The exception is not terrible, the key is to deal with the exception. Some exceptions can be expected in writing. For example, if you want the user to enter 2 numbers for calculation, you must consider that the user may enter a divisor of 0 or enter a string.
When writing code, programmers should take into account the user's operation that may cause exceptions, so as to avoid exceptions through corresponding processing.

7.3.1 Use the try...except statement to catch exceptions and process them

In the previous chapter Python compound statement, we have already touched the try...except statement. This statement is used to catch exceptions. Here we review it again.
The complete command of the try statement includes: try, except, else, and finally sub-statements
The try sub-statement is followed by commands that may run abnormally.
The except sub-statement is followed by the possible exception types (there can be more than one), which will be executed after being caught.
The else sub-statement is followed by the try sub-statement and the command to be executed if no exception occurs. The
finally sub-statement is a command that must be executed.

捕获异常的要点:
1. All exceptions will be passed up layer by layer.
2. The exception type is also a class, and Exception is the base class of all exceptions (all exceptions inherit from exceptions).
3. If you don't know what exception will be generated, you can use the base class of Exception, or simply don't write the exception type, which will catch all exceptions (you can do this, but it is not recommended).
4. Other exception classes also have inheritance relationships. Once an except is caught, other except sub-statements will no longer continue to catch exceptions. Therefore, we must pay attention to the order of writing except sub-statements, and the exception type with a small scope must be written in front.
5. If you want to know the details of the exception, you can use the traceback module. The usage is: traceback.print_exc()

exception inheritance

Here are some examples to illustrate the above points:
异常地传递

def fun1():
    print(1)
    print(1/0)


def fun2():
    print(2)
    fun1()


fun2()

Traceback (most recent call last):
File “E:\BaiduNetdiskWorkspace\FrbPythonFiles\study\test1.py”, line 11, in
fun2()
File “E:\BaiduNetdiskWorkspace\FrbPythonFiles\study\test1.py”, line 8, in fun2
fun1()
File “E:\BaiduNetdiskWorkspace\FrbPythonFiles\study\test1.py”, line 3, in fun1
print(1/0)
ZeroDivisionError: division by zero
2
1

As shown in the above code, the print(1/0) error on line 3 is passed to fun1() on line 8, and then passed to fun2() on line 11.

用Exception捕获所有的异常

try:
    1/0
except Exception:
    print('catch')

catch

try:
    print(b)
except Exception:
    print('catch')

catch

不指定要捕获的异常类(默认捕获所有的异常)

try:
    1/0
except:
    print('catch')

catch

捕获时异常类型顺序问题

try:
    1/0
except ArithmeticError:
    print('arit')
except ZeroDivisionError:
    print('zero')

GOLD

As in the above code, ZeroDivisionError will never be caught, because ZeroDivisionError is a subclass of ArithmeticError, and ArithmeticError will always be captured first.
In actual use, be sure to write ZeroDivisionError capture before ArithmeticError.

获取异常的详细信息

import traceback

try:
    100/0
except:
    traceback.print_exc()

Traceback (most recent call last):
File “E:\BaiduNetdiskWorkspace\FrbPythonFiles\study\test1.py”, line 4, in
100/0
ZeroDivisionError: division by zero

7.3.2 Triggering exceptions

The raise statement supports forcing the specified exception to be triggered. Let's look at 2 examples of Python official websites:
>>> raise NameError('HiThere')

Traceback (most recent call last):
File “”, line 1, in
NameError: HiThere

The only argument to raise is the exception to raise. This parameter must be an exception instance or an exception class (derived from the Exception class). If an exception class is passed, it will be instantiated implicitly by calling a constructor with no parameters:
>>> raise ValueError # shorthand for 'raise ValueError()'
If you just want to determine whether an exception was triggered, but do not plan to handle it exception, you can use the simpler raise statement to re-trigger the exception:

try:
    raise NameError('HiThere')
except NameError:
    print('An exception flew by!')
    raise

An exception flew by!
Traceback (most recent call last):
File “”, line 2, in
NameError: HiThere

7.3.3 Custom exceptions

In addition to Python's own exceptions, developers can also customize exception classes for convenience. But whether directly or indirectly, exceptions should be derived from the Exception class.
Exception classes can be defined to do anything other classes can do, but should generally be kept simple, often providing only properties that allow the corresponding exception handler to extract information about the error.
Most exception names end with "Error", similar to standard exception names.
Many standard modules require custom exceptions to report errors that occur in the functions they define.
自定义异常类

class myError(Exception):
    pass


try:
    print('test')
    raise myError('found error')
except myError as err:
    print('catch')
    print(err)

test
catch
found error

By customizing the exception class, we can use the raise statement to raise a custom exception under specific circumstances when writing a program, and then catch it. In this way, you can better know the running situation of the program and can do corresponding exception handling.

7.3.4 Errors cannot be caught

Because the error did not pass through the interpreter during interpretation, it did not enter the stage of program execution, so the error cannot be caught. as follows:

try:
a = 1/0
    print('我是一只小小鸟)
except SyntaxError:
    print(1)
except ZeroDivisionError:
    print(2)
File "E:\BaiduNetdiskWorkspace\FrbPythonFiles\study\test1.py", line 3
  print('我是一只小小鸟)
        ^

SyntaxError: unterminated string literal (detected at line 3)

This example makes a good distinction between errors and exceptions. We see that the result is reported: SyntaxError error, this is because the code is interpreted first, and then the SyntaxError error is found. This means that this code is not executed, otherwise the ZeroDivisionError error should be caught first.

Guess you like

Origin blog.csdn.net/crleep/article/details/129650144