How to Check If an Exception Has a Certain Message in Python

PythonPythonBeginner
Practice Now

Introduction

In this lab, you will learn how to explore and access exception messages in Python to effectively debug and handle errors. The lab guides you through creating a Python script with a divide function that uses a try...except block to catch potential exceptions during division. You'll observe how different types of exceptions, such as ZeroDivisionError and TypeError, generate specific error messages.

The lab then demonstrates how to access the exception object and its type to gain more detailed information about the error. By running the script with different inputs, you'll see how the exception messages provide valuable insights into the cause of the errors, enabling you to identify and fix issues in your code.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("Python")) -.-> python/ErrorandExceptionHandlingGroup(["Error and Exception Handling"]) python/ErrorandExceptionHandlingGroup -.-> python/catching_exceptions("Catching Exceptions") python/ErrorandExceptionHandlingGroup -.-> python/raising_exceptions("Raising Exceptions") subgraph Lab Skills python/catching_exceptions -.-> lab-559608{{"How to Check If an Exception Has a Certain Message in Python"}} python/raising_exceptions -.-> lab-559608{{"How to Check If an Exception Has a Certain Message in Python"}} end

Explore Exception Messages

In this step, you will learn how to explore exception messages in Python. Exception messages provide valuable information about what went wrong in your code, helping you to debug and fix errors.

First, let's create a Python file named exceptions.py in your ~/project directory using the VS Code editor.

## exceptions.py
def divide(x, y):
    try:
        result = x / y
        print("The result is:", result)
    except Exception as e:
        print("An error occurred:", e)

divide(10, 2)
divide(10, 0)
divide("hello", 5)

In this code:

  • We define a function divide(x, y) that attempts to divide x by y.
  • We use a try...except block to catch any exceptions that might occur during the division.
  • If an exception occurs, we print an error message along with the exception object e.

Now, let's run the exceptions.py script using the python command:

python exceptions.py

You should see the following output:

The result is: 5.0
An error occurred: division by zero
An error occurred: unsupported operand type(s) for /: 'str' and 'int'

As you can see, the first call to divide(10, 2) executes successfully and prints the result. The second call, divide(10, 0), raises a division by zero exception, which is caught by the except block, and the corresponding error message is printed. The third call, divide("hello", 5), raises a TypeError because you can't divide a string by an integer.

Now, let's modify the exceptions.py file to print the type of the exception:

## exceptions.py
def divide(x, y):
    try:
        result = x / y
        print("The result is:", result)
    except Exception as e:
        print("An error occurred:", type(e), e)

divide(10, 2)
divide(10, 0)
divide("hello", 5)

Run the script again:

python exceptions.py

You should see the following output:

The result is: 5.0
An error occurred: <class 'ZeroDivisionError'> division by zero
An error occurred: <class 'TypeError'> unsupported operand type(s) for /: 'str' and 'int'

This output shows the type of each exception that occurred, providing even more information for debugging.

Access Exception args

In this step, you will learn how to access the arguments (args) associated with an exception in Python. Exception arguments can provide more specific details about the error that occurred.

Let's modify the exceptions.py file you created in the previous step to access and print the exception arguments. Open exceptions.py in your ~/project directory using the VS Code editor.

## exceptions.py
def divide(x, y):
    try:
        result = x / y
        print("The result is:", result)
    except Exception as e:
        print("An error occurred:", type(e), e.args)

divide(10, 2)
divide(10, 0)
divide("hello", 5)

In this code, we've modified the except block to print e.args. The args attribute is a tuple containing the arguments that were passed to the exception's constructor.

Now, run the exceptions.py script:

python exceptions.py

You should see the following output:

The result is: 5.0
An error occurred: <class 'ZeroDivisionError'> ('division by zero',)
An error occurred: <class 'TypeError'> ("unsupported operand type(s) for /: 'str' and 'int'",)

As you can see, the output now includes the arguments associated with each exception. For ZeroDivisionError, the argument is a tuple containing the string 'division by zero'. For TypeError, the argument is a tuple containing the string "unsupported operand type(s) for /: 'str' and 'int'".

Let's modify the exceptions.py file again to access the first argument directly:

## exceptions.py
def divide(x, y):
    try:
        result = x / y
        print("The result is:", result)
    except Exception as e:
        print("An error occurred:", type(e), e.args[0])

divide(10, 2)
divide(10, 0)
divide("hello", 5)

Run the script again:

python exceptions.py

You should see the following output:

The result is: 5.0
An error occurred: <class 'ZeroDivisionError'> division by zero
An error occurred: <class 'TypeError'> unsupported operand type(s) for /: 'str' and 'int'

By accessing e.args[0], we can extract the first argument of the exception, which is often the most descriptive part of the error message.

Match the Message String

In this step, you will learn how to match the message string of an exception in Python. This is useful when you want to handle specific types of exceptions differently based on their message.

Let's modify the exceptions.py file you've been working with to catch the ZeroDivisionError specifically and print a custom message. Open exceptions.py in your ~/project directory using the VS Code editor.

## exceptions.py
def divide(x, y):
    try:
        result = x / y
        print("The result is:", result)
    except ZeroDivisionError as e:
        print("Cannot divide by zero!")
    except Exception as e:
        print("An error occurred:", type(e), e.args[0])

divide(10, 2)
divide(10, 0)
divide("hello", 5)

In this code:

  • We've added a specific except block for ZeroDivisionError.
  • If a ZeroDivisionError occurs, we print the message "Cannot divide by zero!".
  • The generic except Exception as e block will catch any other exceptions.

Now, run the exceptions.py script:

python exceptions.py

You should see the following output:

The result is: 5.0
Cannot divide by zero!
An error occurred: <class 'TypeError'> unsupported operand type(s) for /: 'str' and 'int'

As you can see, when divide(10, 0) is called, the ZeroDivisionError is caught by the specific except block, and the custom message "Cannot divide by zero!" is printed. The TypeError raised by divide("hello", 5) is still caught by the generic except block.

You can also match the message string directly, although this is generally less recommended than catching specific exception types. Here's how you can do it:

## exceptions.py
def divide(x, y):
    try:
        result = x / y
        print("The result is:", result)
    except Exception as e:
        if "division by zero" in str(e):
            print("Cannot divide by zero!")
        else:
            print("An error occurred:", type(e), e.args[0])

divide(10, 2)
divide(10, 0)
divide("hello", 5)

In this code:

  • We catch all exceptions in the generic except block.
  • We check if the string "division by zero" is present in the string representation of the exception object e.
  • If it is, we print "Cannot divide by zero!". Otherwise, we print the generic error message.

Run the script again:

python exceptions.py

You should see the same output as before:

The result is: 5.0
Cannot divide by zero!
An error occurred: <class 'TypeError'> unsupported operand type(s) for /: 'str' and 'int'

While matching the message string can be useful in some cases, it's generally better to catch specific exception types because exception messages can change, making your code less reliable.

Summary

In this lab, you explored exception messages in Python to understand how to debug and fix errors. You learned to use a try...except block to catch exceptions during division operations and print the exception object e to view the error message.

You also modified the script to print the type of the exception, gaining further insight into the nature of the errors encountered, such as ZeroDivisionError and TypeError. This allows for more targeted debugging and error handling.