How to Handle Exceptions in Python

09/09/2021

Contents

In this article, you will learn how to handle exceptions in Python.

Handling Exceptions

In Python, exceptions are raised when something unexpected occurs during the execution of a program. Exceptions are handled using the “try-except” statement. Here is an example of how to handle an exception in Python:

try:
   # some code that might raise an exception
   x = int(input("Enter a number: "))
   result = 1 / x
except ValueError:
   print("Invalid input. Please enter a valid number.")
except ZeroDivisionError:
   print("Cannot divide by zero.")
else:
   print(result)

The try block contains the code that might raise an exception. The except block contains the code that will be executed if an exception is raised. In this example, there are two except blocks: one to handle the ValueError exception (raised if the input is not a valid number), and one to handle the ZeroDivisionError exception (raised if the input is zero). If no exception is raised, the code in the else block will be executed.

You can also catch multiple exceptions in a single except block using parentheses, like this:

try:
   # some code that might raise an exception
   x = int(input("Enter a number: "))
   result = 1 / x
except (ValueError, ZeroDivisionError) as e:
   print(f"An error occurred: {e}")
else:
   print(result)

This is useful when the handling for multiple exceptions is the same. The variable e will contain the specific exception that was raised.

You can also raise an exception explicitly using the raise statement. This can be useful for indicating a problem in your code or for testing exception handling. Here is an example:

def square(x):
   if x < 0:
      raise ValueError("Cannot calculate the square of a negative number.")
   return x * x

try:
   x = int(input("Enter a number: "))
   result = square(x)
except ValueError as e:
   print(e)
else:
   print(result)

In this example, the square function raises a ValueError exception if the input is negative. The exception is then caught and handled in the try-except block.