How to Check If a Specific Exception Was Raised in Python

PythonPythonBeginner
Practice Now

Introduction

In this lab, you will learn how to check if a specific exception was raised in Python. The lab focuses on understanding different exception types and how to handle them effectively.

You'll explore common exception types like TypeError, NameError, IndexError, KeyError, ValueError, and FileNotFoundError through practical examples in a Python script. The lab guides you through creating a exceptions_demo.py file and adding code that demonstrates how each exception type is raised and caught using try...except blocks.


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") python/ErrorandExceptionHandlingGroup -.-> python/custom_exceptions("Custom Exceptions") subgraph Lab Skills python/catching_exceptions -.-> lab-559566{{"How to Check If a Specific Exception Was Raised in Python"}} python/raising_exceptions -.-> lab-559566{{"How to Check If a Specific Exception Was Raised in Python"}} python/custom_exceptions -.-> lab-559566{{"How to Check If a Specific Exception Was Raised in Python"}} end

Learn About Exception Types

In this step, you will learn about different types of exceptions in Python. Exceptions are events that disrupt the normal flow of a program's execution. Understanding exception types is crucial for handling errors effectively.

Python has many built-in exceptions, and you can also create your own. Here are some common exception types:

  • TypeError: Raised when an operation or function is applied to an object of inappropriate type.
  • NameError: Raised when a name is not found in the local or global namespace.
  • IndexError: Raised when a sequence subscript is out of range.
  • KeyError: Raised when a dictionary key is not found.
  • ValueError: Raised when an operation or function receives an argument that has the right type but an inappropriate value.
  • FileNotFoundError: Raised when a file or directory is requested but cannot be found.

Let's explore these exception types with some examples. We will create a Python script named exceptions_demo.py in the ~/project directory using the VS Code editor.

  1. Open VS Code.
  2. Create a new file named exceptions_demo.py in the ~/project directory.
  3. Add the following code to the exceptions_demo.py file:
## TypeError
try:
    result = 1 + "a"
except TypeError as e:
    print(f"TypeError: {e}")

## NameError
try:
    print(undefined_variable)
except NameError as e:
    print(f"NameError: {e}")

## IndexError
try:
    my_list = [1, 2, 3]
    print(my_list[5])
except IndexError as e:
    print(f"IndexError: {e}")

## KeyError
try:
    my_dict = {"a": 1, "b": 2}
    print(my_dict["c"])
except KeyError as e:
    print(f"KeyError: {e}")

## ValueError
try:
    num = int("abc")
except ValueError as e:
    print(f"ValueError: {e}")

## FileNotFoundError
try:
    with open("nonexistent_file.txt", "r") as f:
        content = f.read()
except FileNotFoundError as e:
    print(f"FileNotFoundError: {e}")

This script demonstrates how different exception types are raised and caught using try...except blocks. Each try block contains code that might raise a specific exception. If the exception occurs, the corresponding except block is executed.

Now, let's run the script:

  1. Open the terminal in VS Code.
  2. Navigate to the ~/project directory:
cd ~/project
  1. Run the exceptions_demo.py script using the python command:
python exceptions_demo.py

You should see the following output:

TypeError: unsupported operand type(s) for +: 'int' and 'str'
NameError: name 'undefined_variable' is not defined
IndexError: list index out of range
KeyError: 'c'
ValueError: invalid literal for int() with base 10: 'abc'
FileNotFoundError: [Errno 2] No such file or directory: 'nonexistent_file.txt'

This output shows that each try block raised the expected exception, and the corresponding except block caught and printed the exception message.

Understanding different exception types and how to handle them is essential for writing robust and reliable Python code. In the next step, you will learn how to catch specific exceptions and handle them appropriately.

Catch a Specific Exception

In the previous step, you learned about different types of exceptions in Python. Now, you will learn how to catch a specific exception using the try...except block. This allows you to handle different errors in different ways, making your code more robust.

When catching exceptions, it's best practice to be as specific as possible. This prevents your except block from accidentally catching exceptions it wasn't designed to handle, which can mask errors and make debugging harder.

Let's modify the exceptions_demo.py script to catch a specific exception, such as ValueError, when trying to convert a string to an integer.

  1. Open the exceptions_demo.py file in the ~/project directory using VS Code.
  2. Modify the script to catch only the ValueError when converting a string to an integer:
try:
    num = int("abc")
except ValueError as e:
    print(f"ValueError caught: {e}")
except Exception as e:
    print(f"Some other exception: {e}")

print("Continuing execution...")

In this example, we specifically catch the ValueError that occurs when int("abc") fails. If any other exception occurs within the try block, it will be caught by the except Exception as e: block. The print("Continuing execution...") statement will always be executed if any exception is caught, demonstrating that the program continues to run after handling the exception.

Now, let's run the script:

  1. Open the terminal in VS Code.
  2. Navigate to the ~/project directory:
cd ~/project
  1. Run the exceptions_demo.py script using the python command:
python exceptions_demo.py

You should see the following output:

ValueError caught: invalid literal for int() with base 10: 'abc'
Continuing execution...

This output shows that the ValueError was caught, and the program continued to execute.

Now, let's modify the script to raise a different exception, such as TypeError, and see how it's handled:

  1. Open the exceptions_demo.py file in the ~/project directory using VS Code.
  2. Modify the script to raise a TypeError:
try:
    result = 1 + "a"
except ValueError as e:
    print(f"ValueError caught: {e}")
except Exception as e:
    print(f"Some other exception: {e}")

print("Continuing execution...")

Now, run the script again:

python exceptions_demo.py

You should see the following output:

Some other exception: unsupported operand type(s) for +: 'int' and 'str'
Continuing execution...

This output shows that the TypeError was caught by the except Exception as e: block, because there is no specific except TypeError block.

Catching specific exceptions allows you to handle different errors in different ways, making your code more robust and easier to debug. In the next step, you will learn how to verify the exception instance.

Verify the Exception Instance

In this step, you will learn how to verify the exception instance to get more information about the error that occurred. When you catch an exception, you can access the exception object itself, which contains details about the error.

Let's modify the exceptions_demo.py script to print the type and arguments of the exception instance.

  1. Open the exceptions_demo.py file in the ~/project directory using VS Code.
  2. Modify the script to print the type and arguments of the ValueError exception:
try:
    num = int("abc")
except ValueError as e:
    print(f"Exception type: {type(e)}")
    print(f"Exception arguments: {e.args}")
    print(f"ValueError caught: {e}")
except Exception as e:
    print(f"Some other exception: {e}")

print("Continuing execution...")

In this example, we print the type of the exception object using type(e) and the arguments of the exception using e.args. The e.args attribute is a tuple containing the arguments that were passed to the exception's constructor.

Now, let's run the script:

  1. Open the terminal in VS Code.
  2. Navigate to the ~/project directory:
cd ~/project
  1. Run the exceptions_demo.py script using the python command:
python exceptions_demo.py

You should see the following output:

Exception type: <class 'ValueError'>
Exception arguments: ("invalid literal for int() with base 10: 'abc'",)
ValueError caught: invalid literal for int() with base 10: 'abc'
Continuing execution...

This output shows the type of the exception (ValueError) and the arguments passed to the exception's constructor (a tuple containing the error message).

You can use this information to provide more detailed error messages or take specific actions based on the type and arguments of the exception.

For example, you can check if the exception arguments contain a specific error message:

try:
    num = int("abc")
except ValueError as e:
    if "invalid literal" in e.args[0]:
        print("Invalid input: Please enter a valid number.")
    else:
        print(f"ValueError caught: {e}")
except Exception as e:
    print(f"Some other exception: {e}")

print("Continuing execution...")

In this example, we check if the first argument of the ValueError exception contains the string "invalid literal". If it does, we print a more specific error message.

Verifying the exception instance allows you to handle errors more intelligently and provide more informative error messages to the user.

Summary

In this lab, the first step focuses on understanding different exception types in Python, which are crucial for effective error handling. The lab introduces common built-in exceptions such as TypeError, NameError, IndexError, KeyError, ValueError, and FileNotFoundError.

The lab then provides practical examples of how these exceptions are raised and caught using try...except blocks. A Python script named exceptions_demo.py is created to demonstrate each exception type, showing how to anticipate and handle potential errors that may disrupt the normal flow of a program's execution.