Nearby lessons

80 of 159

Python - Multiple Except Blocks

📌 What You Will Learn
  • Use multiple except blocks and understand the top-to-bottom matching order
  • Handle several exception types with a single except block
  • Explain why a child exception block must be written before its parent exception block
  • Know that parentheses are mandatory when a single except block handles multiple exceptions

Multiple except Blocks

The way of handling an exception varies from one exception type to another.

Therefore, for every exception type, a separate except block can be provided.

Python allows multiple except blocks with a single try block. This is recommended whenever different exceptions require different handling logic.

General Syntax

🐍Code Cell
1try:
2 -------
3 -------
4 -------
5 
6except ZeroDivisionError:
7 perform alternative arithmetic operations
8 
9except FileNotFoundError:
10 use local file instead of remote file
Output
No output captured.

Example

🐍Code Cell
1try:
2 x = int(input("Enter First Number: "))
3 y = int(input("Enter Second Number: "))
4 print(x/y)
5 
6except ZeroDivisionError:
7 print("Can't Divide with Zero")
8 
9except ValueError:
10 print("please provide int value only")
Output
No output captured.

Output 1 - No Exception

D:\Python_classes>py test.py

Enter First Number: 10
Enter Second Number: 2

5.0

Output 2 - ZeroDivisionError

D:\Python_classes>py test.py

Enter First Number: 10
Enter Second Number: 0

Can't Divide with Zero

Output 3 - ValueError

D:\Python_classes>py test.py

Enter First Number: 10
Enter Second Number: ten

please provide int value only

Explanation

  • With the input 10 and 2, no exception occurs and 5.0 is printed.
  • With 10 and 0, a ZeroDivisionError is raised, so the except ZeroDivisionError block runs.
  • With 10 and ten, a ValueError is raised, so the except ValueError block runs.

Key Observations

  1. A single try block can have multiple except blocks.
  2. Each except block handles a specific exception type.
  3. Only one matching except block executes for a raised exception.
  4. If no exception occurs, none of the except blocks execute.

Order of Multiple except Blocks

If multiple except blocks are available, the order of these blocks is very important.

The Python Interpreter always checks the except blocks from top to bottom until it finds the first matching exception handler.

Once a matching except block is found, Python executes that block and ignores the remaining except blocks.

Example - Parent Before Child

Output for input 10 and 0:

🐍Code Cell
1try:
2 x = int(input("Enter First Number: "))
3 y = int(input("Enter Second Number: "))
4 print(x/y)
5 
6except ArithmeticError:
7 print("ArithmeticError")
8 
9except ZeroDivisionError:
10 print("ZeroDivisionError")
Output
ArithmeticError

Explanation

ZeroDivisionError is a child class of ArithmeticError.

Python checks the except blocks from top to bottom. Since ZeroDivisionError matches ArithmeticError first, the except ArithmeticError block runs.

The except ZeroDivisionError block is never executed, because the first matching block wins.

Why Order Matters

Correct Order Incorrect Order
Child exception first Parent exception first
Specific exception first General exception first
All handlers can be reached. Some handlers become unreachable.

Single except Block that Can Handle Multiple Exceptions

Sometimes the same handling code is required for multiple exception types.

Instead of writing separate except blocks for every exception, Python allows us to write a single except block that can handle multiple different exception types.

This approach reduces code duplication and makes programs easier to maintain.

Syntax

🐍Code Cell
1except (Exception1, Exception2, Exception3, ...):
2 statements
Output
No output captured.

Syntax with Exception Object

🐍Code Cell
1except (Exception1, Exception2, Exception3, ...) as msg:
2 statements
Output
No output captured.

Important Note

  • Parentheses () are mandatory while specifying multiple exception classes.
  • Internally, Python treats this group of exception classes as a tuple.
  • If any one of the listed exceptions occurs, the same except block executes.

Example

Output 1 - input 10 and 0:

division by zero

Output 2 - input 10 and ten:

invalid literal for int() with base 10: 'ten'
🐍Code Cell
1try:
2 x = int(input("Enter First Number: "))
3 y = int(input("Enter Second Number: "))
4 print(x/y)
5 
6except (ZeroDivisionError, ValueError) as msg:
7 print("Plz Provide valid numbers only and problem is:", msg)
Output
No output captured.

Explanation

If a ZeroDivisionError occurs, the block handles it and the exception object msg contains division by zero.

If a ValueError occurs, the same block executes and msg contains the corresponding description.

Thus, one except block can handle multiple exception types.

Advantages

  1. Reduces duplicate exception handling code.
  2. Makes programs cleaner and easier to read.
  3. Improves maintainability.
  4. Useful when multiple exceptions require the same handling logic.
  5. Supports printing the exception description using the exception object.

Comparison

Separate except Blocks Single except Block
Multiple handlers One handler
More code Less code
Repeated statements No code duplication
Different handling logic Same handling logic
Useful when actions differ Useful when actions are identical
📝 Key Takeaways
  • A single try block can have multiple except blocks, one per exception type
  • Python checks multiple except blocks from top to bottom and runs only the first match
  • If the parent exception appears first, the child handler becomes unreachable
  • One except block can handle several exception types: except (E1, E2) as msg
  • Parentheses are mandatory and Python treats the listed classes as a tuple

🧠 Test Your Knowledge

9 Questions
Progress: 0 / 9