Python 简明教程

Python - User-Defined Exceptions

User-Defined Exceptions in Python

Python 中的用户定义异常是你创建的自定义错误类,用于处理代码中的特定错误条件。它们派生自内置异常类或其任何子类。

User-defined exceptions in Python are custom error classes that you create to handle specific error conditions in your code. They are derived from the built-in Exception class or any of its sub classes.

用户定义的异常提供了对应用程序中错误处理的更精确控制 −

User-defined exceptions provide more precise control over error handling in your application −

  1. Clarity − They provide specific error messages that make it clear what went wrong.

  2. Granularity − They allow you to handle different error conditions separately.

  3. Maintainability − They centralize error handling logic, making your code easier to maintain.

How to Create a User-Defined Exception

要创建一个用户定义的异常,请执行以下步骤 −

To create a user-defined exception, follow these steps −

Step 1 − Define the Exception Class

创建一个新的类,它从内置的“Exception”类或任何其他合适的基类继承。这个新类将作为你的自定义异常。

Create a new class that inherits from the built-in "Exception" class or any other appropriate base class. This new class will serve as your custom exception.

class MyCustomError(Exception):
   pass

Explanation

Explanation

  1. Inheritance − By inheriting from "Exception", your custom exception will have the same behaviour and attributes as the built-in exceptions.

  2. Class Definition − The class is defined using the standard Python class syntax. For simple custom exceptions, you can define an empty class body using the "pass" statement.

Step 2 − Initialize the Exception

实现“ init ”方法以初始化任何属性或提供自定义错误消息。这允许你提高异常时传递有关错误的特定信息。

Implement the "init" method to initialize any attributes or provide custom error messages. This allows you to pass specific information about the error when raising the exception.

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)

Explanation

Explanation

  1. Attributes − Define attributes such as "age" and "message" to store information about the error.

  2. Initialization − The "init" method initializes these attributes. The "super().init(self.message)" call ensures that the base "Exception" class is properly initialized with the error message.

  3. Default Message − A default message is provided, but you can override it when raising the exception.

Step 3 − Optionally Override "str" or "repr"

覆盖“ str ”或“ repr ”方法以提供异常的自定义字符串表示。这对于打印或记录异常很有用。

Override the "str" or "repr" method to provide a custom string representation of the exception. This is useful for printing or logging the exception.

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 __str__(self):
      return f"{self.message}. Provided age: {self.age}"

Explanation

Explanation

  1. str Method − The "str" method returns a string representation of the exception. This is what will be displayed when the exception is printed.

  2. Custom Message − Customize the message to include relevant information, such as the provided age in this example.

Raising User-Defined Exceptions

一旦定义了自定义异常,就可以在代码中提高它以表示特定错误条件。提高用户定义异常涉及使用 raise 语句,该语句可以带或不带自定义消息和属性。

Once you have defined a custom exception, you can raise it in your code to signify specific error conditions. Raising user-defined exceptions involves using the raise statement, which can be done with or without custom messages and attributes.

Syntax

以下是提高异常的基本语法 −

Following is the basic syntax for raising an exception −

raise ExceptionType(args)

Example

在此示例中,“set_age”函数在年龄超出有效范围时引发“InvalidAgeError” −

In this example, the "set_age" function raises an "InvalidAgeError" if the age is outside the valid range −

def set_age(age):
   if age < 18 or age > 100:
      raise InvalidAgeError(age)
   print(f"Age is set to {age}")

Handling User-Defined Exceptions

在 Python 中处理用户定义的异常是指使用“try-except”块来捕获并响应你的自定义异常表示的特定条件。这允许你的程序优雅地处理错误并继续运行,或基于提高的异常类型采取特定操作。

Handling user-defined exceptions in Python refers to using "try-except" blocks to catch and respond to the specific conditions that your custom exceptions represent. This allows your program to handle errors gracefully and continue running or to take specific actions based on the type of exception raised.

Syntax

以下是处理异常的基本语法 −

Following is the basic syntax for handling exceptions −

try:
   # Code that may raise an exception
except ExceptionType as e:
   # Code to handle the exception

Example

在下面的示例中,“try”块使用无效的年龄调用“set_age”。“except”块捕获“InvalidAgeError”并打印自定义错误消息 −

In the below example, the "try" block calls "set_age" with an invalid age. The "except" block catches the "InvalidAgeError" and prints the custom error message −

try:
   set_age(150)
except InvalidAgeError as e:
   print(f"Invalid age: {e.age}. {e.message}")

Complete Example

结合所有步骤,下面是一个创建和使用用户定义异常的完整示例 −

Combining all the steps, here is a complete example of creating and using a user-defined exception −

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 __str__(self):
     return f"{self.message}. Provided age: {self.age}"

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}")

以下是上面代码的输出: -

Following is the output of the above code −

Invalid age: 150. Age must be between 18 and 100