Python program exception handling

1. Exception handling: try-except statement

Insert picture description here
Insert picture description here
The most important part of python exception information is the exception type, which indicates the cause of the exception and is also the basis for the program to handle the exception.
Python uses try-except statements to implement exception handling, and its basic syntax format:

try:
   <语句块1>
except <异常类型>:
   <语句块2>

Add exception handling for the above small program:

try:
    num = eval(input("请输入一个整数:"))
    print(num**2)
except NameError:
    print("输入错误,请输入一个整数!")

The result is:

=
请输入一个整数:NO
输入错误,请输入一个整数!
>>> 

2. Exceptions and Errors Exceptions and errors in
programming languages ​​are two similar but different concepts.
Abnormal (checked exception): predictable exceptions, such as the program expects to get a digital input has been input other characters, open a file that does not exist and so on.
Error (unchecked exception): Some unchecked exceptions due to program coding logic, the program cannot be resumed after the error occurs.
3. Advanced usage of exceptions. The
try-except statement can support multiple except statements. The syntax format is as follows:

try:
    <语句块1>
except <异常类型1>:
    <语句块2>
...
except <异常类型N>:
    <语句块N+1>
except:
    <语句块N+2>
  其中,第1到第N个except语句后面都指定了异常类型,说明这些except所包含的语句块只处理这些类型的异常。最后一个except语句没有指定任何类型,表示它所对应的语句块可以处理所有其他异常。

In addition to the try and except reserved words, exception statements can also be used in conjunction with else and finally reserved words. The syntax format is as follows:

try:                   #放置最想要检测的部分
    <语句块1>
except <异常类型1>:     #放置想要捕获的异常,以及出现异常后的处理
    <语句块2>
else:                   #放置不出现异常时要执行的部分
    <语句块3>
finally:                #放置无论如何都要执行的部分
    <语句块4>

Examples:

try:
    alp = "ABCDEFGHIJKLMNOPQRSUVWXYZ"
    idx = eval(input("请输入一个整数:"))
    print(alp[idx])
except NameError:
    print("输入错误,请输入一个整数!")
else:
    print("没有发生异常。")
finally:
    print("程序执行完毕。")

The result is:

=
请输入一个整数:5
F
没有发生异常。
程序执行完毕。
>>> 
=============== RESTART: F:/软件/python/练习1/text4/try-except.py ===============
请输入一个整数:NO
输入错误,请输入一个整数!
程序执行完毕。
>>> 

Summary:
Python can recognize a variety of exception types, but it is not recommended to rely on try-except as an exception handling mechanism when writing programs. Try-except exceptions are generally only used to detect rare occurrences, for example, the compliance of user input or the success of file opening. In the face of commercial application software products, stability and reliability are one of the most important metrics. Even such products will not abuse try-except type statements. Because the use of try-except statements will affect the readability of the code and increase the difficulty of code maintenance, generally, try-except statements are generally only used in key places to handle possible exceptions.

Guess you like

Origin blog.csdn.net/langezuibang/article/details/106408453