How can I use built-in exceptions in Python?

Published on Aug. 22, 2023, 12:16 p.m.

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.

Tags:

related content