深度阅读

How can I use built-in exceptions in Python?

作者
作者
2023年08月22日
更新时间
12.89 分钟
阅读时间
0
阅读量

To use built-in exceptions in Python, you can follow these steps:

  1. Identify the type of exception you want to raise, for example ZeroDivisionError or IndexError.
  2. Create an instance of the corresponding exception class using the raise keyword.
  3. Include your custom message if desired, by passing it as a string argument to the exception constructor.
  4. Catch the exception using a try-except statement.

Here is an example:

# Example 1: Division by zero
x = 5
y = 0
try:
    result = x / y
except ZeroDivisionError as e:
    print("Error:", e)

# Example 2: Index out of range
my_list = [1, 2, 3]
try:
    value = my_list[3]
except IndexError as e:
    print("Error:", e)

In Example 1, we raise a ZeroDivisionError exception when dividing a number by zero. We catch the exception using a try-except statement and print the error message.

In Example 2, we raise an IndexError exception when trying to access an element in a list that is out of range. Again, we catch the exception using a try-except statement and print the error message.

Note that Python provides numerous built-in exceptions such as TypeError, ValueError, and KeyError amongst others. It is always good practice to use the most appropriate built-in exception for an error.

博客作者

热爱技术,乐于分享,持续学习。专注于Web开发、系统架构设计和人工智能领域。