table of Contents
1. What is an exception?
1. As a programmer, the most likely to encounter are BUGs and errors. It is often mainly due to code problems, network problems, data problems and other reasons that cause program operation errors and cause the program to crash. During the development process, we It is possible to pre-process the possible abnormalities in advance to prevent problems before they occur and reduce the risk of program crashes. I will write about all abnormal problems for you. Let's first look at some abnormal signs:
the signs of exception handling are shown in the figure above. So we are afraid of exceptions, we need to catch exceptions. Preprocessing it, through this article, you can see some basic common exceptions.
More abnormal error display:
ArithmeticError
AssertionError
AttributeError
BaseException
BufferError
BytesWarning
DeprecationWarning
EnvironmentError
EOFError
Exception
FloatingPointError
FutureWarning
GeneratorExit
ImportError
ImportWarning
IndentationError
IndexError
IOError
KeyboardInterrupt
KeyError
LookupError
MemoryError
NameError
NotImplementedError
OSError
OverflowError
PendingDeprecationWarning
ReferenceError
RuntimeError
RuntimeWarning
StandardError
StopIteration
SyntaxError
SyntaxWarning
SystemError
SystemExit
TabError
TypeError
UnboundLocalError
UnicodeDecodeError
UnicodeEncodeError
UnicodeError
UnicodeTranslateError
UnicodeWarning
UserWarning
ValueError
Warning
ZeroDivisionError
2. Catch the exception
(1) Catch exception
Common formats for catching exceptions:
try:
可能产生异常的代码
except Exception as err:
异常处理
For example: we write a simple example, open a file that does not exist, an exception occurs.
file = open("student.txt")
print(file.read())
file.close()
print("文件读取结束!")
Operation result display:
Next, we catch the exception, and we handle the exception;
try:
file = open("student.txt")#读取一个不存在的文件,将产生FileNotFoundError异常
print(file.read())
except FileNotFoundError as err:
print("捕获到异常,文件不存在",err)
print("程序即将结束!")
operation result:
(2) Catch multiple exceptions
The above describes how to catch a single exception, but most of the programs will not come out one, so you need to catch multiple exceptions. To capture multiple exceptions, you only need to store the class name of the exception to be caught in the tuple of except , As long as any one of the exceptions listed in the tuple occurs during the running of the program, it will be caught and processed, and multiple exceptions will be renamed with as.
Syntax format:
try:
可能产生异常的代码块
except (Excepttion Type1,Exception Type2,...)
异常处理
Case: Print a non-existent variable, read a non-existent file
try:
print(num)#打印一个没有定义的变量,将会产生NameError异常
open("student.txt")#读取一个不存在的文件,将产生FileNotFoundError异常
except(NameError,FileNotFoundError)as err:
print("捕获到异常!",err)
print("程序即将结束!")
The NameError exception occurred above. After the exception was caught, the open ("student.txt") was not executed downward, but the exception was processed in the except. After processing, continue to execute the code after try...except...
(3) Catch all exceptions
This time we took measures in advance for possible abnormalities, caught and handled them in time. Equivalent to setting up a preprocessing scheme, python can capture all unpredicted exceptions through the Exception exception class.
try:
open("student.txt")
print(num)
except NameError as err:
print("捕获到异常!",err)
except Exception as err_all:
print("捕获到全部异常!",err_all)
operation result:
3. Finally in the exception
If a piece of code must be executed, regardless of whether an exception occurs or not, then you need to use the finally statement. For example, an exception occurs during database operation, but you still need to return the database connection to the connection pool in the end. In this case, you need to use it finally statement.
try:
f = open("student.txt")
print("打印文件内容")
except FileNotFoundError as err:
print("捕获到异常!",err)
finally:
print("关闭连接!")
Exceptions generated but not caught:
try:
f = open("student.txt")
print("打印文件内容")
finally:
print("关闭连接!")
Operation result:
No exception, execute finally statement.
try:
num = "python"
print(num)
finally:
print("关闭连接!")
operation result:
4. Abnormal delivery
In the development process, we often encounter function nested calls. If the function called inside the function generates an exception, it needs to be caught and processed in the outer function. This requires the exception generated from the internal call function to be passed to the outer function. It is called exception delivery.
def function1():
print(num1)
def function2():
try:
function1()
except Exception as err:
print("捕获到异常!",err)
function2()
operation result:
5.raise throws an exception
ZeroDivisionError with a divisor of 0 is abnormal.
def div(a,b):
if b == 0:
raise ZeroDivisionError
else:
return a/b
div(2,0)
Operation result:
Pass the parameter to the ZeroDivisionError exception, and when the program throws the ZeroDivisionError exception, it will be printed out together with the exception to facilitate understanding of the cause of the exception.
def div(a,b):
if b == 0:
raise ZeroDivisionError("异常原因:除数不能为0!")
else:
return a/b
div(2,0)
operation result: