Exception handling in Python 4-2

As mentioned in "Exception Handling in Python 4-1" , all exceptions can be caught with except. In fact, there are many reasons for exceptions during the running of the program, such as the subscript out of range, the divisor is 0, the variable is undefined, etc.

1 except statement plus specific exception type

You can add a specific exception type after the except statement to indicate that the statement only catches the specified exception. The code is as follows.

a, b = input('请输入被除数和除数:').split()
try:
    print(int(a)/int(b))
except ZeroDivisionError:
    print('除数不能为0。')

Among them, the except statement only captures the ZeroDivisionError exception. When the divisor is 0, Python will throw this exception. The input and output of the program handling the ZeroDivisionError exception are shown in Figure 1.

Figure 1 Handling ZeroDivisionError exception

As can be seen from Figure 1, the value entered after running the program is "1 0", that is, the value of a is "1" and the value of b is "0".

The value of int(b) is 0, and Python will throw a ZeroDivisionError exception. This exception is handled by the code we wrote and displays "the divisor cannot be 0".

When the input is "1 a", the value of b is "a". At this time, int(b) cannot convert it to an integer type, and a ValueError exception will be thrown. However, since our code does not catch the ValueError exception, the exception will be handled by Python, and a red error message will be displayed. The code is shown in Figure 2.

Figure 2 ValueError exception handling

2 Handle multiple exceptions at the same time

For the situation where multiple exceptions may occur in a piece of code mentioned in "1 except statement plus specific exception type", we can use multiple excepts to catch them. The code is as follows.

a, b = input('请输入被除数和除数:').split()
try:
    print(int(a)/int(b))
except ZeroDivisionError:
    print('除数不能为0。')
except ValueError:
    print('输入的不是数字。')

When "1 a" is entered, because the code captures the ValueError exception, "The input is not a number" will be displayed, as shown in Figure 3.

Figure 3 Catching multiple exceptions

Guess you like

Origin blog.csdn.net/hou09tian/article/details/132775308