Multiple Except Blocks Handling
π·οΈ Error Handling and Exceptions / Try-Except Blocks
When writing Python code, different errors can occur at different times. A single try block might encounter various types of problemsβa file might not exist, a value might be invalid, or a network connection might fail. Instead of writing separate try blocks for each possible error, Python allows you to attach multiple except blocks to one try block. This keeps your code clean and lets you handle each error type with its own specific response.
βοΈ Why Use Multiple Except Blocks?
- Granular Control β Each error type gets its own handling logic, so you can respond appropriately to a missing file versus a wrong data type.
- Readable Code β Grouping related error handling in one place makes it easier for others (and your future self) to understand what could go wrong.
- Avoids Generic Catching β Instead of catching all errors with a blanket except, you can be precise and only handle the errors you expect.
π οΈ Basic Structure
The pattern looks like this:
- Start with a try block containing the code that might fail.
- Follow with multiple except blocks, each specifying a different exception type.
- Each except block contains the code to run if that specific error occurs.
Example structure:
- try: Attempt to open a file and read a number from it.
- except FileNotFoundError: Print a message that the file is missing.
- except ValueError: Print a message that the content is not a valid number.
- except PermissionError: Print a message that you don't have access.
Only one except block will executeβthe first one that matches the error that actually occurred.
π΅οΈ Common Exception Types for Engineers
| Exception Type | When It Occurs | Typical Scenario |
|---|---|---|
| FileNotFoundError | A file or directory does not exist | Reading a config file that was deleted |
| ValueError | A function receives an argument with the right type but wrong value | Converting a string like "abc" to an integer |
| TypeError | An operation is applied to an object of inappropriate type | Adding a string to an integer |
| KeyError | A dictionary key is not found | Accessing a missing key in a JSON response |
| IndexError | A list index is out of range | Iterating past the end of a list |
| PermissionError | Insufficient access rights | Writing to a protected log directory |
| ConnectionError | A network connection fails | Reaching a downed API endpoint |
π Comparison: Single Except vs. Multiple Except Blocks
| Aspect | Single Except Block | Multiple Except Blocks |
|---|---|---|
| Error specificity | Catches all exceptions (or one type) | Catches different types individually |
| Code clarity | Can hide unexpected bugs | Clearly shows which errors are expected |
| Maintenance | Harder to update error responses | Easy to add or remove error handlers |
| Best use case | Quick prototyping or cleanup | Production code with known failure modes |
π οΈ Practical Example Walkthrough
Imagine you are writing a script that reads a server's port number from a configuration file.
Step 1 β The try block: You attempt to open the file and convert its content to an integer.
Step 2 β First except block: If the file does not exist, you log a warning and use a default port.
Step 3 β Second except block: If the file exists but contains text like "eight" instead of "8", you catch the ValueError and prompt the user to fix the file.
Step 4 β Third except block: If you lack read permissions, you catch PermissionError and escalate the issue.
Each error leads to a different, meaningful response instead of a generic failure message.
β οΈ Order Matters
Python checks except blocks in the order you write them. Always place more specific exceptions before more general ones.
- Correct order: FileNotFoundError then Exception.
- Wrong order: Exception then FileNotFoundError (the first block catches everything, so the second never runs).
A good rule of thumb: list exceptions from most specific to least specific.
π§ Best Practices
- Only catch what you can handle β If you don't know how to recover from an error, let it propagate up.
- Use the exception object β You can capture the error message by writing except SomeError as e: and then using e in your response.
- Avoid bare except blocks β Using except: without a type catches system-exiting errors like KeyboardInterrupt, which can make your script impossible to stop.
- Keep each except block focused β Each handler should do one thing: log, retry, use a default, or notify.
π Combining with Else and Finally
Multiple except blocks work seamlessly with else and finally:
- else: Runs only if no exception occurred in the try block.
- finally: Always runs, whether an exception happened or not (great for closing files or releasing resources).
This combination gives you full control over the flow of your error handling logic.
β Summary
Multiple except blocks give you the power to anticipate different failure modes and respond to each one appropriately. By structuring your error handling this way, you write more resilient code that is easier to debug and maintain. Start by identifying the specific errors your code might trigger, then write a dedicated except block for each one, ordered from most specific to most general.
Multiple except blocks allow you to catch different types of errors separately within a single try block.
π§ͺ Example 1: Catching two different exception types
This example shows how to handle a ZeroDivisionError and a ValueError with separate except blocks.
try:
number = int(input("Enter a number: "))
result = 10 / number
print("Result:", result)
except ZeroDivisionError:
print("Cannot divide by zero")
except ValueError:
print("Please enter a valid number")
π€ Output: Cannot divide by zero (if user enters 0) or Please enter a valid number (if user enters text)
π§ͺ Example 2: Catching built-in exceptions with specific messages
This example demonstrates catching FileNotFoundError and PermissionError separately when reading a file.
try:
file = open("data.txt", "r")
content = file.read()
file.close()
except FileNotFoundError:
print("The file does not exist")
except PermissionError:
print("You do not have permission to read this file")
π€ Output: The file does not exist (if data.txt is missing)
π§ͺ Example 3: Multiple except blocks with different variable names
This example shows how to access the exception object in each except block.
try:
age = int(input("Enter your age: "))
result = 100 / age
print("Result:", result)
except ValueError as ve:
print("Value error:", ve)
except ZeroDivisionError as zde:
print("Division error:", zde)
π€ Output: Value error: invalid literal for int() with base 10: 'abc' (if user enters "abc")
π§ͺ Example 4: Using multiple except blocks with a list operation
This example handles IndexError and TypeError when working with a list.
try:
items = [10, 20, 30]
index = int(input("Enter index: "))
value = items[index]
result = value + "extra"
print("Result:", result)
except IndexError:
print("Index is out of range")
except TypeError:
print("Cannot add string to number")
π€ Output: Index is out of range (if user enters 5) or Cannot add string to number (if user enters 0)
π§ͺ Example 5: Practical data validation with multiple exceptions
This example validates user input for a simple calculator using multiple except blocks.
try:
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
operation = input("Enter operation (+, -, *, /): ")
if operation == "+":
result = num1 + num2
elif operation == "-":
result = num1 - num2
elif operation == "*":
result = num1 * num2
elif operation == "/":
result = num1 / num2
else:
print("Invalid operation")
result = None
if result is not None:
print("Result:", result)
except ValueError:
print("Please enter valid numbers")
except ZeroDivisionError:
print("Cannot divide by zero")
π€ Output: Please enter valid numbers (if user enters text) or Cannot divide by zero (if user enters 0 for second number and chooses division)
π Comparison Table: Multiple Except Blocks
| Feature | Single Except Block | Multiple Except Blocks |
|---|---|---|
| Number of exceptions caught | One per block | Multiple, one per block |
| Error messages | Same for all errors | Different for each error |
| Code organization | Less specific | More specific and clear |
| Debugging ease | Harder to identify error type | Easier to identify error type |
| Use case | Simple error handling | Complex error handling with different responses |
When writing Python code, different errors can occur at different times. A single try block might encounter various types of problemsβa file might not exist, a value might be invalid, or a network connection might fail. Instead of writing separate try blocks for each possible error, Python allows you to attach multiple except blocks to one try block. This keeps your code clean and lets you handle each error type with its own specific response.
βοΈ Why Use Multiple Except Blocks?
- Granular Control β Each error type gets its own handling logic, so you can respond appropriately to a missing file versus a wrong data type.
- Readable Code β Grouping related error handling in one place makes it easier for others (and your future self) to understand what could go wrong.
- Avoids Generic Catching β Instead of catching all errors with a blanket except, you can be precise and only handle the errors you expect.
π οΈ Basic Structure
The pattern looks like this:
- Start with a try block containing the code that might fail.
- Follow with multiple except blocks, each specifying a different exception type.
- Each except block contains the code to run if that specific error occurs.
Example structure:
- try: Attempt to open a file and read a number from it.
- except FileNotFoundError: Print a message that the file is missing.
- except ValueError: Print a message that the content is not a valid number.
- except PermissionError: Print a message that you don't have access.
Only one except block will executeβthe first one that matches the error that actually occurred.
π΅οΈ Common Exception Types for Engineers
| Exception Type | When It Occurs | Typical Scenario |
|---|---|---|
| FileNotFoundError | A file or directory does not exist | Reading a config file that was deleted |
| ValueError | A function receives an argument with the right type but wrong value | Converting a string like "abc" to an integer |
| TypeError | An operation is applied to an object of inappropriate type | Adding a string to an integer |
| KeyError | A dictionary key is not found | Accessing a missing key in a JSON response |
| IndexError | A list index is out of range | Iterating past the end of a list |
| PermissionError | Insufficient access rights | Writing to a protected log directory |
| ConnectionError | A network connection fails | Reaching a downed API endpoint |
π Comparison: Single Except vs. Multiple Except Blocks
| Aspect | Single Except Block | Multiple Except Blocks |
|---|---|---|
| Error specificity | Catches all exceptions (or one type) | Catches different types individually |
| Code clarity | Can hide unexpected bugs | Clearly shows which errors are expected |
| Maintenance | Harder to update error responses | Easy to add or remove error handlers |
| Best use case | Quick prototyping or cleanup | Production code with known failure modes |
π οΈ Practical Example Walkthrough
Imagine you are writing a script that reads a server's port number from a configuration file.
Step 1 β The try block: You attempt to open the file and convert its content to an integer.
Step 2 β First except block: If the file does not exist, you log a warning and use a default port.
Step 3 β Second except block: If the file exists but contains text like "eight" instead of "8", you catch the ValueError and prompt the user to fix the file.
Step 4 β Third except block: If you lack read permissions, you catch PermissionError and escalate the issue.
Each error leads to a different, meaningful response instead of a generic failure message.
β οΈ Order Matters
Python checks except blocks in the order you write them. Always place more specific exceptions before more general ones.
- Correct order: FileNotFoundError then Exception.
- Wrong order: Exception then FileNotFoundError (the first block catches everything, so the second never runs).
A good rule of thumb: list exceptions from most specific to least specific.
π§ Best Practices
- Only catch what you can handle β If you don't know how to recover from an error, let it propagate up.
- Use the exception object β You can capture the error message by writing except SomeError as e: and then using e in your response.
- Avoid bare except blocks β Using except: without a type catches system-exiting errors like KeyboardInterrupt, which can make your script impossible to stop.
- Keep each except block focused β Each handler should do one thing: log, retry, use a default, or notify.
π Combining with Else and Finally
Multiple except blocks work seamlessly with else and finally:
- else: Runs only if no exception occurred in the try block.
- finally: Always runs, whether an exception happened or not (great for closing files or releasing resources).
This combination gives you full control over the flow of your error handling logic.
β Summary
Multiple except blocks give you the power to anticipate different failure modes and respond to each one appropriately. By structuring your error handling this way, you write more resilient code that is easier to debug and maintain. Start by identifying the specific errors your code might trigger, then write a dedicated except block for each one, ordered from most specific to most general.
Interactive Views
You are currently in π All-in-One mode. Use the tabs at the top to switch to π Theory Only or π» Code Only views.
Multiple except blocks allow you to catch different types of errors separately within a single try block.
π§ͺ Example 1: Catching two different exception types
This example shows how to handle a ZeroDivisionError and a ValueError with separate except blocks.
try:
number = int(input("Enter a number: "))
result = 10 / number
print("Result:", result)
except ZeroDivisionError:
print("Cannot divide by zero")
except ValueError:
print("Please enter a valid number")
π€ Output: Cannot divide by zero (if user enters 0) or Please enter a valid number (if user enters text)
π§ͺ Example 2: Catching built-in exceptions with specific messages
This example demonstrates catching FileNotFoundError and PermissionError separately when reading a file.
try:
file = open("data.txt", "r")
content = file.read()
file.close()
except FileNotFoundError:
print("The file does not exist")
except PermissionError:
print("You do not have permission to read this file")
π€ Output: The file does not exist (if data.txt is missing)
π§ͺ Example 3: Multiple except blocks with different variable names
This example shows how to access the exception object in each except block.
try:
age = int(input("Enter your age: "))
result = 100 / age
print("Result:", result)
except ValueError as ve:
print("Value error:", ve)
except ZeroDivisionError as zde:
print("Division error:", zde)
π€ Output: Value error: invalid literal for int() with base 10: 'abc' (if user enters "abc")
π§ͺ Example 4: Using multiple except blocks with a list operation
This example handles IndexError and TypeError when working with a list.
try:
items = [10, 20, 30]
index = int(input("Enter index: "))
value = items[index]
result = value + "extra"
print("Result:", result)
except IndexError:
print("Index is out of range")
except TypeError:
print("Cannot add string to number")
π€ Output: Index is out of range (if user enters 5) or Cannot add string to number (if user enters 0)
π§ͺ Example 5: Practical data validation with multiple exceptions
This example validates user input for a simple calculator using multiple except blocks.
try:
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
operation = input("Enter operation (+, -, *, /): ")
if operation == "+":
result = num1 + num2
elif operation == "-":
result = num1 - num2
elif operation == "*":
result = num1 * num2
elif operation == "/":
result = num1 / num2
else:
print("Invalid operation")
result = None
if result is not None:
print("Result:", result)
except ValueError:
print("Please enter valid numbers")
except ZeroDivisionError:
print("Cannot divide by zero")
π€ Output: Please enter valid numbers (if user enters text) or Cannot divide by zero (if user enters 0 for second number and chooses division)
π Comparison Table: Multiple Except Blocks
| Feature | Single Except Block | Multiple Except Blocks |
|---|---|---|
| Number of exceptions caught | One per block | Multiple, one per block |
| Error messages | Same for all errors | Different for each error |
| Code organization | Less specific | More specific and clear |
| Debugging ease | Harder to identify error type | Easier to identify error type |
| Use case | Simple error handling | Complex error handling with different responses |