Skip to content

Python Exceptions

New Course Coming Soon:

Get Really Good at Git

It’s important to have a way to handle errors.

Python gives us exception handling.

If you wrap lines of code into a try: block:

try:
    # some lines of code

If an error occurs, Python will alert you and you can determine which kind of error occurred using a except blocks:

try:
    # some lines of code
except <ERROR1>:
    # handler <ERROR1>
except <ERROR2>:
    # handler <ERROR2>

To catch all exceptions you can use except without any error type:

try:
    # some lines of code
except <ERROR1>:
    # handler <ERROR1>
except:
    # catch all other exceptions

The else block is ran if no exceptions were found:

try:
    # some lines of code
except <ERROR1>:
    # handler <ERROR1>
except <ERROR2>:
    # handler <ERROR2>
else:
    # no exceptions were raised, the code ran successfully

A finally block lets you perform some operation in any case, regardless if an error occurred or not

try:
    # some lines of code
except <ERROR1>:
    # handler <ERROR1>
except <ERROR2>:
    # handler <ERROR2>
else:
    # no exceptions were raised, the code ran successfully
finally:
    # do something in any case

The specific error that’s going to occur depends on the operation you’re performing.

For example if you are reading a file, you might get an EOFError. If you divide a number by zero you will get a ZeroDivisionError. If you have a type conversion issue you might get a TypeError.

Try this code:

result = 2 / 0
print(result)

The program will terminate with an error

Traceback (most recent call last):
  File "main.py", line 1, in <module>
    result = 2 / 0
ZeroDivisionError: division by zero

and the lines of code after the error will not be executed.

Adding that operation in a try: block lets us recover gracefully and move on with the program:

try:
    result = 2 / 0
except ZeroDivisionError:
    print('Cannot divide by zero!')
finally:
    result = 1

print(result) # 1

You can raise exceptions in your own code, too, using the raise statement:

raise Exception('An error occurred!')

This raises a general exception, and you can intercept it using:

try:
    raise Exception('An error occurred!')
except Exception as error:
    print(error)

You can also define your own exception class, extending from Exception:

class DogNotFoundException(Exception):
    pass

pass here means “nothing” and we must use it when we define a class without methods, or a function without code, too.

try:
    raise DogNotFoundException()
except DogNotFoundException:
    print('Dog not found!')
→ Get my Python Handbook
→ Get my Python Handbook

Here is how can I help you: