What Is an Exception?
An exception is an error that occurs during program execution and, if unhandled, crashes your program. Python provides try/except blocks to handle these errors gracefully instead of letting the program stop.
print(10 / 0) # ❌ ZeroDivisionError: division by zero — program crashes
Basic try / except
try:
result = 10 / 0
except ZeroDivisionError:
print("You can't divide by zero!")
Catching Multiple Exceptions
try:
num = int(input("Enter a number: "))
result = 10 / num
except ValueError:
print("That's not a valid number!")
except ZeroDivisionError:
print("You can't divide by zero!")
Catching Any Exception
try:
risky_code()
except Exception as e:
print("Something went wrong:", e)
Tip: catching the generic Exception is fine for logging, but prefer catching specific exceptions whenever you know what could go wrong.
else and finally
try:
result = 10 / 2
except ZeroDivisionError:
print("Error occurred")
else:
print("No errors — result is", result) # runs only if no exception
finally:
print("This always runs") # runs no matter what
Raising Your Own Exceptions
def enroll(age):
if age < 16:
raise ValueError("Minimum enrollment age is 16")
print("Enrollment successful!")
try:
enroll(12)
except ValueError as e:
print("Enrollment failed:", e)
Common Built-in Exceptions
| Exception | When It Occurs |
|---|---|
| ValueError | Invalid value, e.g. int("abc") |
| TypeError | Wrong type used in an operation |
| ZeroDivisionError | Dividing by zero |
| KeyError | Dictionary key doesn't exist |
| IndexError | List index out of range |
| FileNotFoundError | File doesn't exist when opening |
Custom Exceptions
class InsufficientFundsError(Exception):
pass
def withdraw(balance, amount):
if amount > balance:
raise InsufficientFundsError("Not enough balance!")
return balance - amount
try:
withdraw(1000, 5000)
except InsufficientFundsError as e:
print(e)
Key Takeaways
- Use
try/exceptto handle errors without crashing your program elseruns only if no exception occurred;finallyalways runs- Use
raiseto trigger your own exceptions, including custom exception classes - Catch specific exceptions whenever possible instead of a generic
Exception