Article directory
Exceptions and handling and usage in Python
abnormal
During the running of the program, some errors will inevitably occur, such as:
using a variable that has not been assigned a value,
using a non-existent index,
dividing by 0
...
We call these errors in the program exceptions.
During the running of the program, once an exception occurs, the program will terminate immediately, and all codes after the exception will not be executed!
Handle exceptions
When an exception occurs while the program is running, the purpose is not to terminate our program directly!
Python hopes that when an exception occurs, we can write code to handle the exception!
try statement
try:
代码块(可能出现错误的语句)
except 异常类型 as 异常名:
代码块(出现错误以后的处理方式)
except 异常类型 as 异常名:
代码块(出现错误以后的处理方式)
except 异常类型 as 异常名:
代码块(出现错误以后的处理方式)
else:
代码块(没出错时要执行的语句)
finally:
代码块(该代码块总会执行)
Try is a must. It doesn’t matter if the else statement is there or not.
There must be at least one except and finally.
You can put the code that may go wrong into a try statement, so that if the code has no errors, it will be executed normally.
If an error occurs, the code in the expect clause will be executed, so that we can handle exceptions through code
to avoid an exception. Causes the entire program to terminate
Propagation of exceptions (throwing exceptions)
When an exception occurs in a function, if the exception is handled in the function, the exception will not continue to propagate.
If the exception is not handled in the function, the exception will continue to propagate to the function call.
If the function call handles If an exception is received, it will no longer be propagated. If it is not handled, it will continue to be propagated to the calling place
until it is passed to the global scope (main module). If it is still not handled, the program will terminate and the exception information will be displayed.
When an exception occurs while the program is running, all exception information will be saved in a special exception object.
When the exception propagates, the exception object is actually thrown to the calling site.
For example: The object of the ZeroDivisionError class is specially used to represent division by 0. The exception
object of the NameError class is specially used to handle variable error exceptions
...etc.
When the program is running, if no exception handling is performed, the exception will continue to propagate until it is passed to the global scope (main module), at which time the program will terminate and display the exception information.
Here's an example:
def fn():
raise ValueError("这是一个自定义的异常")
def main():
try:
fn()
except ValueError as e:
print("发生了异常:", e)
main()
print("程序结束")
In the above code, fn()
the function uses raise
a statement to throw an ValueError
exception, and the exception information is specified as "This is a custom exception". In main()
the function, use try-except
the statement to catch ValueError
the exception and print out the exception information. Finally, output "Program End".
throw an exception
You can use the raise statement to throw an exception.
The raise statement needs to be followed by an exception class or an instance of the exception.
When using exception handling in code, we can use raise
statements to throw custom exceptions or re-throw caught exceptions.
Here's an example:
def divide(x, y):
try:
if y == 0:
raise ZeroDivisionError("除数不能为零")
result = x / y
except ZeroDivisionError as e:
print(e)
raise # 重新引发已捕获的异常
else:
print("结果:", result)
try:
divide(10, 2)
divide(10, 0)
except ZeroDivisionError as e:
print("捕获异常:", e)
In the above code, when the divisor is zero, we raise
raise the built-in ZeroDivisionError
exception through the statement and pass in the error message. At the same time, except ZeroDivisionError
use raise
statements in the block to re-throw the caught exception to continue processing the exception externally.
When using throw exception, we can choose to pass an instance of the exception class or use the class name to raise the exception directly. In this case we used the latter, viz raise ZeroDivisionError("除数不能为零")
.
In the main code block, we try-except
use it to catch ZeroDivisionError
exceptions and print out the caught exception information. This allows you to handle divide()
exceptions thrown by functions.
The output is as follows:
结果: 5.0
division by zero
捕获异常: division by zero
By using raise
statements, we can explicitly raise exceptions in our code and handle or pass them on as needed. This makes exception handling more flexible and controllable, helping to write robust code.
try-except statement
In Python, we can use try-except
statements to catch and handle exceptions of specified types. In addition to catching specific types of exceptions, we can also use try-except
multiple except
blocks of statements to handle different types of exceptions separately.
Here's an example:
def divide(x, y):
try:
result = x / y
print("结果:", result)
except ZeroDivisionError:
print("除数不能为零")
except TypeError:
print("类型错误:无法进行除法运算")
except ValueError:
print("数值错误")
divide(10, 2)
divide(10, 0)
divide(10, "2")
In the above code, divide()
the function is used to calculate the division of two numbers and print the result. The division operation is performed in try
a block and if an exception occurs, the corresponding except
block is executed based on the exception type.
The first time it is called divide(10, 2)
, since the divisor is not zero, no exception is triggered and the result is output.
When called for the second time divide(10, 0)
, the divisor is zero and an exception is triggered ZeroDivisionError
. The program will execute the corresponding except ZeroDivisionError
block and print "The divisor cannot be zero".
When called for the third time divide(10, "2")
, the divisor is of string type and division cannot be performed. An exception is triggered TypeError
. The program will execute the corresponding except TypeError
block and print "Type Error: Division cannot be performed".
The output is as follows:
结果: 5.0
除数不能为零
类型错误:无法进行除法运算
By using multiple except
blocks, you can write specific handling code for different exception types, allowing your program to handle a variety of possible exceptions more accurately. This improves program robustness and reliability.
finally statement
In addition to using try-except
statements to handle exceptions, you can also use finally
clauses to define blocks of code that need to be executed regardless of whether an exception occurs. finally
The code block in the clause will try
be executed after the code in the block is executed regardless of whether an exception occurs.
Here's an example:
def divide(x, y):
try:
result = x / y
except ZeroDivisionError:
print("除数不能为零")
finally:
print("执行finally代码块")
divide(10, 2)
divide(10, 0)
In the above code, divide()
the function is used to calculate the division of two numbers and print the result, using try-except-finally
statements to handle exceptions.
On the first call divide(10, 2)
, since the divisor is non-zero, no exception is triggered, so the result is printed and finally
the code block is executed. The output is as follows:
结果: 5.0
执行finally代码块
On the second call , the divider is zero, an exception is divide(10, 0)
triggered , the exception is caught and an error message is printed, and execution of the code block continues. The output is as follows:ZeroDivisionError
finally
除数不能为零
执行finally代码块
finally
As you can see, the code in the code block will be executed regardless of whether an exception occurs .
finally
Clauses are usually used to release resources, such as closing files, releasing locks, etc. It ensures that no matter whether an exception occurs, some necessary cleaning operations will be performed to ensure the stability and security of the program.
else statement
In addition to try-except
statements, you can also use else
clauses to define try
a block of code that is executed when no exception occurs within the block.
Here's an example:
def divide(x, y):
try:
result = x / y
except ZeroDivisionError:
print("除数不能为零")
else:
print("结果:", result)
divide(10, 2)
divide(10, 0)
In the above code, divide()
the function is used to calculate the division of two numbers and print the result. Perform division operations in try
a block. If a divide-by-zero exception occurs, the program will execute the corresponding except ZeroDivisionError
block and print "The divisor cannot be zero." If no exception occurs, the program executes else
the code block in the clause and prints the result.
The first time it is called divide(10, 2)
, since the divisor is not zero, no exception is triggered and the result is output.
When called for the second time divide(10, 0)
, the divisor is zero and an exception is triggered ZeroDivisionError
. The program will execute the corresponding except ZeroDivisionError
block and print "The divisor cannot be zero" without executing else
the code block in the clause.
The output is as follows:
结果: 5.0
除数不能为零
By using else
clauses, you can place normal processing logic else
inside, making your code clearer and more concise. In this way, we can clearly distinguish exception handling and normal logic processing, improving the readability and maintainability of the code.
Custom exception type
In addition, if we need to customize the exception type, we can Exception
create a new exception type by inheriting the built-in class and use this type when an exception needs to be thrown.
Here's an example:
class MyError(Exception):
def __init__(self, msg):
self.msg = msg
def divide(x, y):
try:
if y == 0:
raise MyError("除数不能为零")
result = x / y
except MyError as e:
print(e.msg)
else:
print("结果:", result)
finally:
print("执行清理操作")
divide(10, 2)
divide(10, 0)
In the above code, we Exception
created a new exception type by inheriting the class MyError
and passed an error message in its constructor. In divide()
the function, we throw a custom exception when dividing by zero MyError
, and catch and handle this exception. else
If no exception occurs, the code block in the clause is executed and the result is printed. finally
Regardless of whether an exception occurs, the code block in the clause is finally executed and "Performing cleanup operation" is printed.
The output is as follows:
结果: 5.0
执行清理操作
除数不能为零
执行清理操作
By customizing exception types, we can better organize and manage our own code, improving the readability and maintainability of the code. At the same time, it can also handle different types of abnormal situations more flexibly to meet different business needs.
Summarize
This article introduces the use and handling of exceptions in Python. Exceptions are errors or exceptional conditions that occur during program execution and can be caught and handled by using the try-except statement.
The article first explains what exceptions are and describes the importance of exception handling. Next, we introduced how to use the try-except statement to catch and handle exceptions. The code in the try block may throw an exception, while the code in the except block will only be executed when the corresponding exception occurs.
The article also mentioned the finally statement, which allows us to define a block of code that will be executed regardless of whether an exception occurs. This is useful for ensuring resources are released or cleaned up.
In addition, the article also introduces the else statement, which can be used to specify the code to be executed when no exception is thrown in the try block. This way we can take different actions depending on whether an exception occurs.
Finally, the article also mentioned the importance and usage of custom exception types. By defining our own exception classes, we can better organize and handle specific exception situations, making the code more readable and maintainable.
Through the introduction of this article, readers can learn how to handle exceptions in Python and how to use the exception mechanism to write more robust code. At the same time, familiarity with the related concepts and syntax of exception handling will help readers better debug and handle error conditions in the program.