w3resource

Catching specific exceptions in Python with multiple except blocks

Explain how we can catch specific exceptions using multiple except blocks.

We can catch specific exceptions using multiple "except" blocks in a Python "try...except" statement. Each "except" block handles a specific type of exception, allowing us to provide custom handling for different exception scenarios. The basic syntax is as follows:

try:
    # Code that may raise exceptions
except ExceptionType1:
    # Code to handle ExceptionType1
except ExceptionType2:
    # Code to handle ExceptionType2
# ...
except ExceptionTypeN:
    # Code to handle ExceptionTypeN

In the above syntax:

  • "try" contains the code that may raise exceptions.
  • Each "except" block is followed by the type of exception (ExceptionType1, ExceptionType2, etc.) that it should catch.
  • We can place the code to handle exceptions of a particular type in the indented block following each "except" block.

Here is an example:

Code:

try:
    n = int(input("Input a number: "))
    result = 100 / n
except ValueError:
    print("Invalid input. Please input a valid integer.")
except ZeroDivisionError:
    print("Division by zero is not allowed.")
except Exception as e:
    print(f"An unexpected error occurred: {e}")

Output:

Input a number: a
Invalid input. Please input a valid integer.
 
Input a number: 0
Division by zero is not allowed.

In the above example,

  • The first "except" block catches "ValueError" if the user inputs something that cannot be converted to an integer.
  • The second "except" block catches "ZeroDivisionError" if the user enters zero as the denominator.
  • The third "except" block catches any other exceptions that inherit from the "Exception" base class, providing a generic error message for unanticipated issues.


Follow us on Facebook and Twitter for latest update.