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.
- Open the
exceptions_demo.py
file in the ~/project
directory using VS Code.
- 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:
- Open the terminal in VS Code.
- Navigate to the
~/project
directory:
cd ~/project
- 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:
- Open the
exceptions_demo.py
file in the ~/project
directory using VS Code.
- 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.