Skip to content

Python Exceptions

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!')
→ Download my free Python Handbook!

THE VALLEY OF CODE

THE WEB DEVELOPER's MANUAL

You might be interested in those things I do:

  • Learn to code in THE VALLEY OF CODE, your your web development manual
  • Find a ton of Web Development projects to learn modern tech stacks in practice in THE VALLEY OF CODE PRO
  • I wrote 16 books for beginner software developers, DOWNLOAD THEM NOW
  • Every year I organize a hands-on cohort course coding BOOTCAMP to teach you how to build a complex, modern Web Application in practice (next edition February-March-April-May 2024)
  • Learn how to start a solopreneur business on the Internet with SOLO LAB (next edition in 2024)
  • Find me on X

Related posts that talk about python: