0
0
Pythonprogramming~5 mins

Multiple exception handling in Python

Choose your learning style9 modes available
Introduction

Sometimes, a program can have different kinds of errors. Multiple exception handling helps us catch and fix each type separately.

When you want to handle different errors in different ways.
When your program might fail for several reasons and you want clear messages for each.
When you want to keep your program running even if one part causes an error.
When debugging to know exactly what kind of error happened.
Syntax
Python
try:
    # code that might cause an error
except ExceptionType1:
    # handle ExceptionType1
except ExceptionType2:
    # handle ExceptionType2
except ExceptionType3 as e:
    # handle ExceptionType3 and use variable e
else:
    # code if no exception happens
finally:
    # code that runs no matter what

You can have many except blocks after one try.

The else block runs only if no exceptions happen.

Examples
This code handles two errors: if input is not a number, or if dividing by zero.
Python
try:
    x = int(input('Enter a number: '))
    y = 10 / x
except ValueError:
    print('That was not a number!')
except ZeroDivisionError:
    print('Cannot divide by zero!')
This code handles file errors and always closes the file.
Python
file = None
try:
    file = open('data.txt')
    data = file.read()
except FileNotFoundError:
    print('File not found!')
except IOError:
    print('Error reading file!')
else:
    print('File read successfully')
finally:
    if file:
        file.close()
Sample Program

This program asks for a number, divides 100 by it, and handles two errors separately. It always prints a done message.

Python
try:
    num = int(input('Enter a number: '))
    result = 100 / num
except ValueError:
    print('Oops! That is not a valid number.')
except ZeroDivisionError:
    print('Oops! Cannot divide by zero.')
else:
    print(f'Result is {result}')
finally:
    print('Done with the calculation.')
OutputSuccess
Important Notes

Order matters: put more specific exceptions before general ones.

Use as e to get the error message if you want to show it.

The finally block runs no matter what, useful for cleanup.

Summary

Multiple exception handling lets you catch different errors separately.

Use multiple except blocks after one try.

Remember else runs if no error, and finally always runs.