Specific Exceptions
In this tutorial, we'll catch the exact errors you expect.
Good exception handling catches the errors you expect.
try:
number = int("hello")
except ValueError:
print("That is not a number")
This catches ValueError, but it does not hide unrelated problems.
Multiple except Blocks
You can handle different exceptions differently:
values = ["10", "0"]
try:
first = int(values[0])
second = int(values[1])
print(first / second)
except ValueError:
print("Both values must be numbers")
except ZeroDivisionError:
print("The second number cannot be zero")
except IndexError:
print("Missing value")
Each error gets a specific message.
Why Specific Is Better
Imagine this:
try:
result = prices["apple"] / quantity
except Exception:
print("Could not calculate")
This hides many possible problems. Maybe "apple" is missing. Maybe quantity is zero. Maybe prices is the wrong type.
Specific exceptions help you understand and fix the real issue.
Catching More Than One Type
If two errors should use the same message, group them:
try:
number = int(value)
except (TypeError, ValueError):
print("Please provide a number")
Read the Error Name
When deciding what to catch, first run the code without try / except and read the exception name in the traceback. If Python says ValueError, catch ValueError. If it says KeyError, catch KeyError.
This keeps your error handling connected to the real problem.
Practice
Write code that reads a value from a dictionary and divides it by a number. Handle KeyError and ZeroDivisionError separately.