How to Check If an Exception Was Raised in Python

PythonPythonBeginner
Practice Now

Introduction

In this lab, you will learn how to check if an exception was raised in Python. The lab focuses on understanding exceptions and using try-except blocks to catch and handle them, preventing program crashes.

You'll start by creating a Python script that raises a ZeroDivisionError exception. Then, you'll learn how to use a try-except block to catch this exception and handle it gracefully, allowing your program to continue running.


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-559611{{"How to Check If an Exception Was Raised in Python"}} python/raising_exceptions -.-> lab-559611{{"How to Check If an Exception Was Raised in Python"}} end

Understand Exceptions

In this step, you will learn about exceptions in Python. Exceptions are events that occur during the execution of a program that disrupt the normal flow of instructions. Understanding exceptions is crucial for writing robust and reliable Python code.

When an error occurs in Python, an exception is raised. If the exception is not handled, the program will terminate and display an error message. However, by using try-except blocks, you can catch and handle exceptions, preventing your program from crashing.

Let's start with a simple example that raises an exception:

  1. Open the VS Code editor in the LabEx environment.

  2. Create a new file named division.py in the ~/project directory.

    ~/project/division.py
  3. Add the following code to the division.py file:

    numerator = 10
    denominator = 0
    result = numerator / denominator
    print(result)

    This code attempts to divide 10 by 0, which is an invalid operation and will raise a ZeroDivisionError exception.

  4. Run the script using the following command in the terminal:

    python division.py

    You will see an output similar to this:

    Traceback (most recent call last):
      File "/home/labex/project/division.py", line 3, in <module>
        result = numerator / denominator
    ZeroDivisionError: division by zero

    The traceback shows that a ZeroDivisionError occurred on line 3 of the division.py file. The program terminated because the exception was not handled.

Now, let's see how to handle this exception using a try-except block.

Use try-except to Catch

In this step, you will learn how to use try-except blocks to catch and handle exceptions in Python. This allows your program to continue running even when errors occur.

The basic structure of a try-except block is as follows:

try:
    ## Code that might raise an exception
except ExceptionType:
    ## Code to handle the exception

The code inside the try block is executed. If an exception of type ExceptionType occurs, the code inside the except block is executed. If no exception occurs, the except block is skipped.

Let's modify the division.py file from the previous step to handle the ZeroDivisionError exception:

  1. Open the division.py file in the VS Code editor.

  2. Modify the code to include a try-except block:

    try:
        numerator = 10
        denominator = 0
        result = numerator / denominator
        print(result)
    except ZeroDivisionError:
        print("Error: Cannot divide by zero.")

    In this code, the try block contains the division operation that might raise a ZeroDivisionError. The except block catches the ZeroDivisionError and prints an error message.

  3. Run the script using the following command in the terminal:

    python division.py

    You will see the following output:

    Error: Cannot divide by zero.

    Instead of crashing, the program now gracefully handles the ZeroDivisionError and prints an informative message.

This demonstrates how try-except blocks can be used to prevent your program from crashing due to exceptions.

Inspect the Exception Type

In this step, you will learn how to inspect the exception type and access the exception message within the except block. This allows you to handle different types of exceptions in different ways and provide more informative error messages.

When an exception is caught, you can assign it to a variable in the except clause using the as keyword:

try:
    ## Code that might raise an exception
except ExceptionType as e:
    ## Code to handle the exception
    ## 'e' is the exception object

The variable e will then contain the exception object, which you can use to access information about the exception, such as its type and message.

Let's modify the division.py file to inspect the exception type and print the exception message:

  1. Open the division.py file in the VS Code editor.

  2. Modify the code to inspect the exception type and print the message:

    try:
        numerator = 10
        denominator = 0
        result = numerator / denominator
        print(result)
    except ZeroDivisionError as e:
        print(f"Error: {type(e).__name__} - {e}")

    In this code, we catch the ZeroDivisionError and assign it to the variable e. We then use type(e).__name__ to get the name of the exception type and e to get the exception message. We print both in a formatted string.

  3. Run the script using the following command in the terminal:

    python division.py

    You will see the following output:

    Error: ZeroDivisionError - division by zero

    The output now includes the exception type (ZeroDivisionError) and the exception message (division by zero).

This allows you to provide more detailed information about the error that occurred, making it easier to debug your code. You can also use this information to handle different types of exceptions in different ways, providing more specific error handling for each case.

Summary

In this lab, you learned about exceptions in Python, which are events that disrupt the normal flow of a program. When an error occurs, an exception is raised, and if unhandled, the program terminates.

You also learned how to use try-except blocks to catch and handle exceptions, preventing program crashes. The lab demonstrated a ZeroDivisionError and how to use try-except to handle it.