Chapter 7: Exception handling

Handling exceptions

face Josiah Wang

In Python, an Exception is an error that occurs when your program is executing. Compare that to syntax errors, which happens when Python compiles your program before executing it. We will not be able to handle such errors, so please do not let me see any syntax errors in your assignments! You will be severely punished! 🔥🐍🔥🐍🔥

For simplicity, we will use the terms Error and Exception interchangeably. When we say Error, we generally mean Exception.

As discussed in the video, when you expect a piece of code to raise an exception, you enclose it in a try block. You can then catch any exceptions in the try block, and you deal with them in the except block.

try:
    a = int(input("a = "))
    b = int(input("b = "))
    print("a/b = ", a/b) 
except ZeroDivisionError: 
    print("b should not be zero.") 

You can target specific Exceptions to catch. Any other Exceptions will be left to the Python runtime interpreter to handle.

try:
    a = int(input("a = "))
    b = int(input("b = "))
    print(f"a/b = {a/b}") 
except ValueError: 
    print("Cannot convert your input to a number.") 
except ZeroDivisionError: 
    print("b should not be zero.") 

You can also handle multiple types of Exceptions together, in case you are handling them in the same way (remember the Don’t Repeat Yourself (DRY) principle!)

try:
    a = int(input("a = "))
    b = int(input("b = "))
    print(f"a/b = {a/b}") 
except (ValueError, ZeroDivisionError): 
    print("Invalid input. You must enter non-zero integers.") 

Python recommends that you keep your try blocks small. Each try block should target only a specific error. This way, it will be easier to keep track of where you’re expecting errors, making your code easier to maintain.

try:
    a = int(input("a = "))
    b = int(input("b = "))
except ValueError: 
    print("Cannot convert your input to a number.") 
    exit()

try:
    print(f"a/b = {a/b}") 
except ZeroDivisionError: 
    print("b should not be zero.")