Python Exception Handling

Exception handling

In computing and computer programming, exception handling is the process of responding to the occurrence of exceptions – anomalous or exceptional conditions requiring special processing.

Python has many built-in exceptions that are raised when a program encounters an error, and most external libraries, like the popular Requests, include his own custom exceptions that we will need to deal to.

Basic exception handling

You can’t divide by zero, that is a mathematical true, and if you try to do it in Python, the interpreter will raise the built-in exception ZeroDivisionError:

def divide(dividend , divisor):
    print(dividend / divisor)

divide(dividend=10, divisor=5)
2
divide(dividend=10, divisor=0)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ZeroDivisionError: division by zero

Let’s say we don’t want our program to stop its execution or show the user an output he will not understand. Say we want to print a useful and clear message, then we need to handle the exception with the try and except keywords:

# try-except: handle exceptions gracefully
def divide(dividend , divisor):
    try:  # Try to execute this code
        print(dividend / divisor)
    except ZeroDivisionError:  # Catch specific exception type
        print('You can not divide by 0')

divide(dividend=10, divisor=5)
2
divide(dividend=10, divisor=0)
You can not divide by 0
Quiz

Sign in to answer this quiz and track your learning progress

What keywords are used to handle exceptions in Python?
A. try and except
B. catch and handle
C. error and rescue
D. if and else

Handling Multiple exceptions using one exception block

You can also handle multiple exceptions in one line like the following without the need to create multiple exception blocks.

# Handle multiple exceptions in one except block
def divide(dividend , divisor):
    try:
        if (dividend == 10):
          var = 'str' + 1  # This will raise TypeError
        else:
          print(dividend / divisor)
    except (ZeroDivisionError, TypeError) as error:  # Catch multiple exception types
        print(error)  # Print the error message

divide(dividend=20, divisor=5)
4
divide(dividend=10, divisor=5)
can only concatenate str (not "int") to str
divide(dividend=10, divisor=0)
division by zero
Quiz

Sign in to answer this quiz and track your learning progress

Can you handle multiple exception types in a single except block?
A. No, you must use separate except blocks for each exception type
B. Yes, by putting them in a tuple like except (Exception1, Exception2)
C. Yes, but only if they are related
D. No, Python doesn't support this

Finally code in exception handling

The code inside the finally section is always executed, no matter if an exception has been raised or not:

# finally block: always executes regardless of exceptions
def divide(dividend , divisor):
    try:
        print(dividend / divisor)
    except ZeroDivisionError:
        print('You can not divide by 0')
    finally:  # Always executes, even if exception occurs
        print('Execution finished')

divide(dividend=10, divisor=5)
2.0
Execution finished
divide(dividend=10, divisor=0)
You can not divide by 0
Execution finished
Quiz

Sign in to answer this quiz and track your learning progress

When does the finally block execute?
A. Only when an exception occurs
B. Only when no exception occurs
C. Always, regardless of whether an exception occurred or not
D. Never

Custom Exceptions

Custom exceptions initialize by creating a class that inherits from the base Exception class of Python, and are raised using the raise keyword:

# Custom exception: create by inheriting from Exception class
class MyCustomException(Exception):
    pass

raise MyCustomException  # Raise the custom exception
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
__main__.MyCustomException

To declare a custom exception message, you can pass it as a parameter:

class MyCustomException(Exception):
    pass

raise MyCustomException('A custom message for my custom exception')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
__main__.MyCustomException: A custom message for my custom exception

Handling a custom exception is the same as any other:

try:
    raise MyCustomException('A custom message for my custom exception')
except MyCustomException:
    print('My custom exception was raised')
My custom exception was raised
Quiz

Sign in to answer this quiz and track your learning progress

How do you create a custom exception in Python?
A. Create a class that inherits from the Exception class
B. Use the @exception decorator
C. Call Exception.create()
D. Import it from a special module