Handling Multiple Exceptions
Part of the Logic & Flow section of Coddy's Python journey — lesson 65 of 78.
In Python, we can handle different types of exceptions in separate except blocks. This allows us to respond differently based on the specific error that occurs.
Start with a basic try-except structure:
try:
# Code that might raise exceptions
pass
except Exception as e:
# Handle any exception
passTo handle multiple exceptions, add specific except blocks:
try:
number = int(input("Enter a number: "))
result = 10 / number
print(result)
except ValueError:
print("That's not a valid number!")
except ZeroDivisionError:
print("Cannot divide by zero!")You can also catch multiple exception types in a single except block:
try:
# Some code
pass
except (ValueError, TypeError):
print("Invalid input type!")The order of except blocks matters - always place more specific exceptions before more general ones.
Challenge
EasyCreate a function called process_data that:
- Takes a string input representing potential data
- Tries to convert it to an integer, then calculates 100 divided by that integer
- Returns the result
- Handles at least 3 possible exceptions:
ValueErrorif the input cannot be converted to an integer (print "Input must be a number!")ZeroDivisionErrorif the input is 0 (print "Cannot divide by zero!")- Any other exception with a generic handler (print "An unexpected error occurred!")
Cheat sheet
Handle different types of exceptions using multiple except blocks:
try:
number = int(input("Enter a number: "))
result = 10 / number
print(result)
except ValueError:
print("That's not a valid number!")
except ZeroDivisionError:
print("Cannot divide by zero!")Catch multiple exception types in a single except block:
try:
# Some code
pass
except (ValueError, TypeError):
print("Invalid input type!")Always place more specific exceptions before more general ones in the order of except blocks.
Try it yourself
def process_data(input_string):
try:
# Try to convert the input string to an integer
# Calculate 100 divided by the input value
# Return the result
except ValueError:
# Handle the case where input cannot be converted to an integer
except ZeroDivisionError:
# Handle the case where input is zero
except:
# Handle any other unexpected exceptions
return NoneThis lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Variables Exploration
ConstantsMultiple Variable AssignmentsSwapping VariablesPlaceholder VariablesRound NumbersList Casting4Contact Book Application
Display MenuAdd Contact7Sets Part 2
Mathematical Operations Part 1Mathematical Operations Part 2Recap - Treasure HuntSubsets and SupersetsIterating Over SetsRecap - Tournament Tracker2Dictionaries Part 1
What is a Dictionary?Creating a DictionaryAccessing ValuesModifying DictionariesRecap - Recipe Manager5Advanced Decision Making
Ternary OperatorMembership ChecksIdentity ChecksIndentation ErrorsRecap - Vacation Filter8Student Records Manager
Project OverviewAdd Student11Advanced Functions
Returning Multiple ValuesLambda Functions Part 1Lambda Functions Part 2Recap Challenge - Lambda SortRecursive Functions Part 1Recursive Functions Part 2Recap - Sum Nested List14Higher-Order Functions
The Map FunctionThe Filter FunctionRecap - Email ValidatorRecap - Number Processor3Dictionaries Part 2
Dictionary MethodsNested DictionariesChecking for KeysLooping Through DictionariesRecap - Frequency Counter9Advanced Data Aggregation
Using SumFinding Minimum and MaximumSorting Data EfficientlyRecap - Dictionary Sorter12Basic Error Handling
What is Error Handling?The Try and Except BlockHandling Multiple ExceptionsRecap - Shopping Cart Errors