Multiple Exceptions in Python
Learn how to handle multiple types of exceptions in Python
using multiple except blocks.
What are Multiple Exceptions?
A Python program can generate different types of exceptions during execution.
For example, converting invalid text into a number can cause
a ValueError, while dividing a number by zero
can cause a ZeroDivisionError.
Multiple exceptions allow us to handle different exceptions separately.
except blocks.
Multiple Exception Flow
try Block
Python executes the code that may cause an exception.
ValueError
Python moves to the ValueError handler.
ZeroDivisionError
Python moves to the ZeroDivisionError handler.
Matching except Block
The matching exception handler executes.
Basic Syntax
try:
# code that may cause an exception
except ValueError:
# handle ValueError
except ZeroDivisionError:
# handle ZeroDivisionError
Python checks the except blocks and executes
the one that matches the exception.
Simple Example
try:
number = int(input("Enter a number: "))
result = 100 / number
print(result)
except ValueError:
print("Please enter a valid number")
except ZeroDivisionError:
print("Cannot divide by zero")
Example Output:
Enter a number: abc
Please enter a valid number
Enter a number: 0
Cannot divide by zero
The program handles both exceptions separately.
Handling ValueError
A ValueError occurs when a value is not
valid for the requested operation.
try:
number = int("abc")
print(number)
except ValueError:
print("Invalid number")
Output:
Invalid number
Handling ZeroDivisionError
A ZeroDivisionError occurs when a number
is divided by zero.
try:
result = 10 / 0
print(result)
except ZeroDivisionError:
print("Cannot divide by zero")
Output:
Cannot divide by zero
Handling TypeError
A TypeError can occur when an operation
is performed between incompatible data types.
try:
result = "10" + 5
print(result)
except TypeError:
print("Invalid data types")
Output:
Invalid data types
Handling IndexError
An IndexError occurs when we try to access
a list position that does not exist.
numbers = [10, 20, 30]
try:
print(numbers[5])
except IndexError:
print("Invalid index")
Output:
Invalid index
Handling KeyError
A KeyError occurs when a dictionary key
does not exist.
student = {
"name": "Rahul",
"course": "Python"
}
try:
print(student["fees"])
except KeyError:
print("Key not found")
Output:
Key not found
Multiple Exceptions with User Input
User input can produce different exceptions, so we can handle each one separately.
try:
first = int(
input("Enter first number: ")
)
second = int(
input("Enter second number: ")
)
result = first / second
print("Result:", result)
except ValueError:
print("Please enter numbers only")
except ZeroDivisionError:
print("Second number cannot be zero")
This example handles both invalid input and division by zero.
Multiple Exceptions with Same Handling
If different exceptions require the same response,
we can handle them inside one except block.
try:
number = int(input("Enter a number: "))
result = 100 / number
print(result)
except (ValueError, ZeroDivisionError):
print("Invalid input or division by zero")
Output:
Invalid input or division by zero
Parentheses are used to specify multiple exception types.
Using as with Multiple Exceptions
We can store the exception object in a variable using
the as keyword.
try:
number = int("abc")
except ValueError as error:
print("Error:", error)
Output:
Error: invalid literal for int() with base 10: 'abc'
The variable error contains information
about the exception.
Order of except Blocks
Python checks the except blocks from top
to bottom.
Specific exception handlers should be written before
a general Exception handler.
try:
number = int("abc")
except ValueError:
print("Invalid number")
except Exception:
print("Some other error occurred")
Python first checks ValueError. If the
exception matches, that block is executed.
Using the General Exception Class
We can use Exception to catch many
standard exceptions.
try:
result = 10 / 0
except Exception as error:
print("Error:", error)
Use specific exception types whenever practical so that the actual problem is clear.
Example: Student Marks 👀🌍
try:
marks = int(
input("Enter student marks: ")
)
if marks < 0 or marks > 100:
print("Marks must be between 0 and 100")
else:
print("Valid marks:", marks)
except ValueError:
print("Please enter a valid number")
This example handles invalid user input using
ValueError.
Best Practices
Specific Exceptions
Catch the expected exception type whenever practical.
Clear Messages
Provide useful information about the problem.
Simple Handling
Keep exception handling clear and easy to understand.
Common Mistakes
- Using the wrong exception type.
-
Using a completely generic
exceptwithout understanding the error. -
Putting too much code inside the
tryblock. - Not providing a useful error message.
- Placing a general exception handler before a specific exception handler.
Practice Programs
-
Handle
ValueErrorandZeroDivisionErrorseparately. -
Create a calculator using multiple
exceptblocks. -
Handle an invalid list index using
IndexError. -
Handle a missing dictionary key using
KeyError. -
Handle two exception types using one
exceptblock. -
Print the exception message using
as error.
Summary
Multiple exception handling allows Python programs to
handle different types of errors safely. We can use
separate except blocks for different
exceptions or handle multiple exception types in one
block when the handling is the same. Common examples
include ValueError,
ZeroDivisionError,
TypeError,
IndexError and
KeyError.