Python 简明教程
Python - Custom Exceptions
What are Custom Exceptions in Python?
Python custom exceptions 是用户定义的错误类,它扩展了基础异常类。开发人员可以定义和处理对自己的应用程序来说是唯一的特定错误条件。通过创建自定义异常,开发人员可以改进自己的代码。这样可以提供更有意义的错误消息,并通过指出发生了什么类型的错误并且该错误源自何处来方便调试过程。
Python custom exceptions are user-defined error classes that extend the base Exception class. Developers can define and handle specific error conditions that are unique to their application. Developers can improve their code by creating custom exceptions. This allows for more meaningful error messages and facilitates the debugging process by indicating what kind of error occurred and where it originated.
为了定义唯一的异常,我们通常必须创建新类,该类从 Python 的内置异常类或其子类之一获取其名称。相应的 except 块可用于触发此自定义类并捕获它。
To define a unique exception we have to typically create a new class that takes its name from Python’s built-in Exception class or one of its subclasses. A corresponding except block can be used to raise this custom class and catch it.
当发生特定错误时,开发人员可以控制程序流程并采取适当的操作,诸如记录错误、重试操作或正常关闭应用程序。自定义异常可以通过覆盖 init 方法并将额外的信息存储为实例属性来携带有关错误的其他上下文或数据。
Developers can control the flow of the program when specific errors occur and take appropriate actions such as logging the error, retrying operations or gracefully shutting down the application. Custom exceptions can carry additional context or data about the error by overriding the init method and storing extra information as instance attributes.
使用自定义异常提高了复杂程序中错误处理的清晰度。它有助于区分可能需要不同处理策略的不同类型的错误。例如,当文件解析库可能定义文件格式错误、字段缺失错误或字段无效错误等异常来处理文件处理过程中可能出现的各种问题时。这种粒度级别通过提高软件的鲁棒性和用户体验,使客户端代码能够更有效地捕获和解决特定问题。Python 的自定义异常是处理错误和更具表现力的代码编写的绝佳工具。
Using custom exceptions improves the clarity of error handling in complex programs. It helps to distinguish between different types of errors that may require different handling strategies. For example when a file parsing library might define exceptions like FileFormatError, MissingFieldError or InvalidFieldError to handle various issues that can arise during file processing. This level of granularity allows the client code to catch and address specific issues more effectively by improving the robustness and user experience of the software. Python’s custom exceptions are a great tool for handling errors and writing better with more expressive code.
Why to Use Custom Exceptions?
Python 中的自定义异常提供了多种优势,它增强了我们的代码的功能、可读性和可维护性。以下是使用自定义异常的主要原因:
Custom exceptions in Python offer several advantages which enhances the functionality, readability and maintainability of our code. Here are the key reasons for using custom exceptions −
-
Specificity: Custom exceptions allow us to represent specific error conditions that are unique to our application.
-
Clarity: They make the code more understandable by clearly describing the nature of the errors.
-
Granularity: Custom exceptions allow for more precise error handling.
-
Consistency: They help to maintain a consistent error-handling strategy across the codebase.
Creating Custom Exceptions
在 Python custom exceptions 中创建涉及定义新的异常类,这些类扩展 Python 的内置异常类或其任何子类。这样,开发人员就可以在自己的应用程序中创建专门针对特定场景的错误类型。以下是我们如何有效地创建和使用自定义异常的方法:
Creating custom exceptions in Python involves defining new exception classes that extend from Python’s built-in Exception class or any of its subclasses. This allows developers to create specialized error types that cater to specific scenarios within their applications. Here’s how we can create and use custom exceptions effectively −
Define the Custom Exception Class
我们可以通过定义从异常或其他异常类(如 RuntimeError、ValueError 等)继承的新类来开始创建自定义异常,具体取决于错误的性质。
We can start creating the custom exceptions by defining a new class that inherits from Exception or another exception class such as RuntimeError, ValueError, etc. depending on the nature of the error.
以下是定义自定义异常类的示例。在此示例中,CustomError 是一个从 Exception 继承的自定义异常类。 init method 用可选的错误消息初始化异常:
Following is the example of defining the custom exception class. In this example CustomError is a custom exception class that inherits from Exception. The init method initializes the exception with an optional error message −
class CustomError(Exception):
def __init__(self, message):
super().__init__(message)
self.message = message
Raise the Custom Exception
为了触发自定义异常,我们可以使用 raise 语句,后跟自定义异常类的实例。另外,我们可以传递一条消息以提供有关错误的上下文信息。
To raise the custom exception we can use the raise statement followed by an instance of our custom exception class. Optionally we can pass a message to provide context about the error.
在此函数 process_data() 中,当数据参数为空时触发 CustomError 异常,具体说明了特定错误条件。
In this function process_data() the CustomError exception is raised when the data parameter is empty by indicating a specific error condition.
def process_data(data):
if not data:
raise CustomError("Empty data provided")
# Processing logic here
Handle the Custom Exception
为了处理自定义异常,我们必须使用 try-except block 。在 except 块中捕获自定义异常类并根据需要处理错误。
To handle the custom exception we have to use a try-except block. Catch the custom exception class in the except block and handle the error as needed.
下面的代码中,如果 process_data([]) 引发了 CustomError,则 except 块会捕获它,我们就能打印错误消息 (e.message) 或执行其他错误处理任务。
Here in the below code if process_data([]) raises a CustomError then the except block catches it and we can print the error message (e.message) or perform other error-handling tasks.
try:
process_data([])
except CustomError as e:
print(f"Custom Error occurred: {e.message}")
# Additional error handling logic
Example of Custom Exception
以下是 Python 中自定义异常处理的基本示例。在该示例中,我们通过子类化内置 Exception 类来定义一个自定义异常,并使用 try-except 块来处理该自定义异常 -
Following is the basic example of custom exception handling in Python. In this example we define a custom exception by subclassing the built-in Exception class and use a try-except block to handle the custom exception −
# Define a custom exception
class CustomError(Exception):
def __init__(self, message):
self.message = message
super().__init__(self.message)
# Function that raises the custom exception
def check_value(value):
if value < 0:
raise CustomError("Value cannot be negative!")
else:
return f"Value is {value}"
# Using the function with exception handling
try:
result = check_value(-5)
print(result)
except CustomError as e:
print(f"Caught an exception: {e.message}")