Python 简明教程
Python - Raising Exceptions
Raising Exceptions in Python
在 Python 中,您可以使用 raise 语句显式引发异常。引发异常使您能够指示出现了错误并通过适当处理这些异常来来控制程序的流程。
In Python, you can raise exceptions explicitly using the raise statement. Raising exceptions allows you to indicate that an error has occurred and to control the flow of your program by handling these exceptions appropriately.
引发异常是指在您的程序中显式触发一个错误条件。对于由于错误或意外情况而导致您的程序正常流程无法继续的情况,这很有用。
Raising an exception refers to explicitly trigger an error condition in your program. This can be useful for handling situations where the normal flow of your program cannot continue due to an error or an unexpected condition.
在 Python 中,您可以引发内置的异常(例如 ValueError 或 TypeError)来指示常见的错误条件。此外,您还可以创建并引发自定义异常。
In Python, you can raise built-in exceptions like ValueError or TypeError to indicate common error conditions. Additionally, you can create and raise custom exceptions.
Raising Built-in Exceptions
您可以通过创建异常类的实例并使用 raise 语句引发任何内置异常。以下是语法 -
You can raise any built-in exception by creating an instance of the exception class and using the raise statement. Following is the syntax −
raise Exception("This is a general exception")
Example
这是一个示例,其中当一个函数接收到一个无效参数时,我们引发一个 ValueError -
Here is an example where we raise a ValueError when a function receives an invalid argument −
def divide(a, b):
if b == 0:
raise ValueError("Cannot divide by zero")
return a / b
try:
result = divide(10, 0)
except ValueError as e:
print(e)
以下是上面代码的输出: -
Following is the output of the above code −
Cannot divide by zero
Raising Custom Exceptions
除了内置异常之外,您还可以通过创建一个新的异常类并继承自基础异常类或其任何子类来定义并引发您自己的自定义异常 -
In addition to built-in exceptions, you can define and raise your own custom exceptions by creating a new exception class that inherits from the base Exception class or any of its subclasses −
class MyCustomError(Exception):
pass
def risky_function():
raise MyCustomError("Something went wrong in risky_function")
try:
risky_function()
except MyCustomError as e:
print(e)
以上代码的输出如下所示 −
Output of the above code is as shown below −
Something went wrong in risky_function
Creating Custom Exceptions
自定义异常对于处理特定于您应用程序的特定错误条件很有用,可提供更精确的错误报告和控制。
Custom exceptions is useful for handling specific error conditions that are unique to your application, providing more precise error reporting and control.
要在 Python 中创建自定义异常,您需要定义一个从内置 Exception 类或任何其他适当的内置异常类继承的新类。此自定义异常类可以具有其他属性和方法,以提供有关错误条件的更详细的上下文。
To create a custom exception in Python, you define a new class that inherits from the built-in Exception class or any other appropriate built-in exception class. This custom exception class can have additional attributes and methods to provide more detailed context about the error condition.
Example
在此示例中 -
In this example −
-
We define a custom exception class "InvalidAgeError" that inherits from "Exception".
-
The init() method initializes the exception with the invalid age and a default error message.
-
The set_age() function raises "InvalidAgeError" if the provided age is outside the valid range.
class InvalidAgeError(Exception):
def __init__(self, age, message="Age must be between 18 and 100"):
self.age = age
self.message = message
super().__init__(self.message)
def set_age(age):
if age < 18 or age > 100:
raise InvalidAgeError(age)
print(f"Age is set to {age}")
try:
set_age(150)
except InvalidAgeError as e:
print(f"Invalid age: {e.age}. {e.message}")
获得的结果如下所示 −
The result obtained is as shown below −
Invalid age: 150. Age must be between 18 and 100
Re-Raising Exceptions
有时,您可能需要捕获一个异常,执行特定操作(例如记录、清理或提供其他上下文),然后重新引发相同的异常以供调用栈进一步处理。
Sometimes, you may need to catch an exception, perform specific actions (such as logging, cleanup, or providing additional context), and then re-raise the same exception to be handled further up the call stack
当您想确保在异常发生时执行某些操作,但仍然允许异常传播以用于更高级别的处理时,这很有用。
This is useful when you want to ensure certain actions are taken when an exception occurs, but still allow the exception to propagate for higher-level handling.
要在 Python 中重新引发异常,您需要使用不指定异常的“raise”语句,这将重新引发当前作用域中活动的最后一个异常。
To re-raise an exception in Python, you use the "raise" statement without specifying an exception, which will re-raise the last exception that was active in the current scope.
Example
在以下示例中 -
In the following example −
-
The process_file() function attempts to open and read a file.
-
If the file is not found, it prints an error message and re-raises the "FileNotFoundError" exception.
-
The exception is then caught and handled at a higher level in the call stack.
def process_file(filename):
try:
with open(filename, "r") as file:
data = file.read()
# Process data
except FileNotFoundError as e:
print(f"File not found: {filename}")
# Re-raise the exception
raise
try:
process_file("nonexistentfile.txt")
except FileNotFoundError as e:
print("Handling the exception at a higher level")
执行上面的代码后,我们得到以下输出: -
After executing the above code, we get the following output −
File not found: nonexistentfile.txt
Handling the exception at a higher level