Python Exception Handling
try:
x = int(input("Enter a number: "))
print(100 / x)
except ValueError:
print("That's not a number")
except ZeroDivisionError:
print("Cannot divide by zero")
else:
print("No error occurred")
finally:
print("Done")
Enter a number: 0
Cannot divide by zero
Done
| Block | Runs when |
|---|---|
| try | Always (code that may fail) |
| except | A matching exception is raised |
| else | No exception occurred |
| finally | Always, even after return or an error |
Raising Custom Exceptions
class AgeError(Exception):
pass
def vote(age):
if age < 18:
raise AgeError("Must be 18+")
return "Eligible"
try:
vote(16)
except AgeError as e:
print("Error:", e)
Error: Must be 18+
Track your progress through the Python course