Skip to main content

Python Exceptions Handling

To manage exceptions, Python uses try, except, else, and finally blocks to catch and handle them gracefully, allowing programs to continue running or terminate in a controlled manner.

Basic Blocks for Exceptions Handling

  • try: This block contains the code that might raise an exception.
    • If an exception occurs within the try block, the rest of the try block is skipped, and the program moves to the except block.
  • except: This block is executed when an exception is raised in the try block.
    • You can specify the type of exception to catch, or you can catch all exceptions by simply writing except: without specifying a type.
    • If the except block handles the exception, the program continues after the except block. If not, the exception is passed up to outer try statements or, if unhandled, terminates the program.
  • else: This block is optional and is executed if the try block does not raise an exception. It must come after all except blocks.
    • The else block is useful for code that should only run when no exceptions occur.
  • finally: This block is optional and is always executed, whether an exception is raised or not.
    • It is commonly used for cleanup actions, such as closing files or releasing resources.

The order of these blocks is the following:

try:
# code that may raise an exception
except ExceptionType1:
print("Executed when ExceptionType1 is raised in try block")
except ExceptionType2:
print("Executed when ExceptionType2 is raised in try block")
# other except blocks...
else:
print("Optional but executed if try-block does not raise an exception.")
finally:
print("Optional but always executed if present.")
print("End of program.")
note

You can handle multiple types of exception by specifying multiple except clauses!

Common Exception Handling in Python

Let's see some common combinations of blocks for handling exceptions in Python.

Python try...except statement

The try...except block is used to handle exceptions in Python.

  • The code that might generate an exception inside the try block.
  • When an exception occurs, it is caught by the except block.

For example

try:
# Code that may raise an exception
result = 10 / 0
except ZeroDivisionError:
# Code to execute if a ZeroDivisionError is raised
print("You can not divide by zero.")

Python try...except...finally statement

The finally block lets you specify a block of code that will be executed regardless of whether an exception was raised in the try block. This is typically used for cleanup actions in your program.

For example:

try:
# Code that may raise an exception
result = 10 / 0
except ZeroDivisionError:
# Code to execute if a ZeroDivisionError is raised
print("You can not divide by zero.")
finally:
# Code to execute no matter what happens above
print("This is the finally block.")

Python try...except...else...finally statement

The else block allows you to specify a block of code that will be executed if no exceptions were raised in the try block.

This is useful for defining code that should only run when no errors occur.

For example:

try:
# Code that may raise an exception
result = 10 / 2
except ZeroDivisionError:
# Code to execute if a ZeroDivisionError is raised
print("You cannot divide by zero.")
else:
# Code to execute if no exceptions were raised
print(f"The result is {result}")
finally:
# Code to execute no matter what happens above
print("This is the finally block.")

Additional features for Exceptions Handling

Handling multiple exceptions

For each try block, there can be zero or more except blocks. Multiple except blocks allow us to handle each exception differently. The argument type of each except block indicates the type of exception that can be handled by it.

try:
# code that may cause an exception
except Exception1 as e1:
# handle exception
except Exception2 as e2:
# handle exception
except Exception3 as e3:
# handle exception

For example, here the odd_numbers list is accessed at index 8: this will raise a IndexError exception because the length of the list is 5, the first index starts from 0 and the last element is at index 4.

try:
odd_numbers = [1,3,5,7,9]
print(odd_numbers[8])
result = 10 / 0

except ZeroDivisionError:
print("Denominator cannot be 0.")

except IndexError:
print("Index Out of Bound.")

Observe that when the IndexError exception occurs in the try block:

  • The ZeroDivisionError exception is skipped.
  • The code inside the IndexError block is executed.

Catch multiple Exceptions with single except clause

If you want to have the same response to some types of exceptions, you can group them into one except clause:

try:
# code that may cause an exception
except (Exception1, Exception2):
# handle exception

For example, here the same except clause catch both ZeroDivisionError and IndexError exceptions:

try:
odd_numbers = [1,3,5,7,9]
print(odd_numbers[8])
result = 10 / 0

except (ZeroDivisionError, IndexError):
print("An error occurred!")

Catch all possible Exceptions

You can catch all standard exceptions that derive from the base Exception class by using the except Exception statement.

try:
# code that may cause an exception
except Exception:
# handle exception

For example

try:
# Code that may raise an exception
result = 10 / 0
except Exception as e:
# Code to execute if any exception derived from Exception is raised
print(f"An error occurred: {e}")
danger

By using except Exception, you can not catch system exceptions like KeyboardInterrupt and SystemExit, which are derived from the BaseException class instead of Exception.