Skip to main content

How to Catch a Specific Exception in Python

· 4 min read
Jagdish Kumawat
Founder @ Dewiride

When something goes wrong, Python raises an exception, and the script stops unless something catches it. Catching one specific kind, such as ValueError, lets you handle the problem you expected while every other error still stops the script and shows you where it happened.

Syntax​

Syntax
try:
<code that may fail>
except <ExceptionClass> as <err>:
<handle it, for example print(<err>)>
PartWhat it does
try:Runs the code that may raise an exception.
except <ExceptionClass>Runs only for that class of exception, or a subclass of it.
as <err>Optional. Puts the exception in a variable; str(err) is its message.

The Python tutorial: "If an exception occurs during execution of the try clause, the rest of the clause is skipped. Then, if its type matches the exception named after the except keyword, the except clause is executed, and then execution continues after the try/except block."

The Example​

The example turns text into a whole number. When the text isn't a number, it catches the ValueError, prints the reason and returns 0.

Prerequisites​

  • uv and Python. This guide uses uv 0.13.10 with Python 3.15.2.

Step 1: Write the Code​

Create a file named main.py:

main.py, which defines to_number(text) that returns int(text) inside try, catches ValueError as err, prints Not a number: with err and returns 0, and prints to_number("42") and to_number("forty-two").

main.py
def to_number(text):
try:
return int(text)
except ValueError as err:
print(f"Not a number: {err}")
return 0


print(to_number("42"))
print(to_number("forty-two"))

int("forty-two") raises a ValueError, which the except clause catches.

Step 2: Run It​

Terminal
uv run python main.py
Output
42
Not a number: invalid literal for int() with base 10: 'forty-two'
0

A zsh terminal where uv run python main.py prints 42, Not a number: invalid literal for int() with base 10: 'forty-two', and 0.

The first call never touched the except clause. The second raised ValueError, the clause printed its message, and the script carried on. The command is the same in zsh, bash and PowerShell.

Catching a Base Class​

Exception classes form a family tree. The tutorial puts it this way: "A class in an except clause matches exceptions which are instances of the class itself or one of its derived classes." ValueError is a subclass of Exception, so except Exception: would catch it too, along with most other errors. issubclass(ValueError, Exception) returns True.

Catch the specific class when only that failure is expected, and a base class when a whole family of failures, such as every error a library defines, should be handled the same way.

Common Mistakes​

MistakeWhat happensDo this instead
A bare except:It also catches KeyboardInterrupt, so even Ctrl+C is swallowedName the class you expect
Catching Exception around a lot of codeReal bugs are handled as if they were the expected failureKeep try small and the class specific
Catching an exception and doing nothingThe problem disappears silentlyAt least print or log err

Troubleshooting​

SymptomLikely causeFix
The script still stops with a tracebackThe exception isn't the class you namedRead its class name on the last line of the traceback and catch that
NameError: name 'err' is not defined after the except blockPython deletes err when the block endsUse err inside the block, or copy it to another name

FAQ​

Can one except catch several classes?​

Yes. Name them together, for example except (ValueError, TypeError):.

How do I find which exception a line raises?​

Run it without try and read the last line of the traceback: it starts with the class name, such as ValueError.

Conclusion​

try runs the risky code and except SomeError as err: handles that kind of failure, with the message in err. Name the class you expect so every other error still surfaces.

Additional Resources​