Python Exceptions
1. What is an Exception?
An exception is an error raised when something invalid happens in your program.
int("hello") # → ValueError: invalid literal for int() with base 10: 'hello'
Common exception types:
| Exception | When it occurs |
|---|---|
ValueError |
Invalid value (e.g. converting "hello" to int) |
ZeroDivisionError |
Dividing by zero |
IndexError |
Accessing an index that doesn't exist |
KeyError |
Accessing a dictionary key that doesn't exist |
SyntaxError |
Invalid Python syntax |
When an exception is not handled, the program crashes immediately.
2. Try / Except Block
Wrap code that might fail in a try block. If an exception occurs, the except block runs instead of crashing.
try:
int("hello") # this raises a ValueError
except:
print("Exception occurred!")
print("Done") # still runs
- If no exception occurs →
exceptblock is skipped - If an exception occurs →
exceptblock runs, then program continues
3. Catching Specific Exceptions
Accept only a specific type of exception and store it in a variable.
try:
int("hello")
except ValueError as e:
print("Value error:", e)
Multiple except blocks
try:
result = 1 / 0
except ValueError as e:
print("Value exception:", e)
except ZeroDivisionError as e:
print("Zero division exception:", e)
- Only the first matching except block runs
- If the exception type doesn't match any block, the program still crashes
Catch any exception
try:
int("hello")
except Exception as e:
print("Any exception:", e)
⚠️ Avoid catching a general
Exceptionunless necessary — it makes bugs harder to find. Prefer catching specific exception types.
4. Finally Block
The finally block always runs, regardless of whether an exception occurred or not. Used for cleanup operations.
try:
int("hello")
except ValueError as e:
print("Error:", e)
finally:
print("This always runs") # runs no matter what
Use case: Restore state, close files, release resources — anything that must happen whether the try succeeds or fails.
5. Raising Your Own Exceptions
Use the raise keyword to throw an exception manually.
raise ValueError("This is not a valid number!")
raise Exception("Something went wrong.")
raise IndexError("Index out of range.")
Practical example — validate user input
num = input("Enter a number: ")
if not num.isdigit():
raise ValueError("This is not a valid number!")
6. Practical Example — Loop Until Valid Input
Use try/except inside a while loop to keep asking until valid input is given.
while True:
num = input("Enter a number: ")
try:
num = float(num)
break # valid float → exit loop
except ValueError:
print("Not a valid float, try again!")
7. Compile Time vs Runtime Errors
| Compile Time Error | Runtime Error | |
|---|---|---|
| When it occurs | Before code runs (during conversion to bytecode) | While code is executing |
| Example | SyntaxError (missing colon, bad indentation) |
ValueError, ZeroDivisionError, IndexError |
| Can you catch it? | ❌ No — code won't even start | ✅ Yes — with try/except |
| Predictable? | ✅ Always fails | ❌ May or may not occur depending on input |
# Compile time error — code won't even run
while True # SyntaxError: missing colon
# Runtime error — only fails on bad input
float(input("Enter a number: ")) # crashes if user types "hello"
8. Recommended Conventions
- Only wrap code in
try/exceptwhen you know an exception might occur - Catch specific exceptions rather than a general
Exception - Use
finallyfor cleanup that must always happen - Use
raiseto give helpful error messages when your code is used incorrectly
Cheat Sheet
# Basic try/except
try:
# risky code
except:
# runs if any exception occurs
# Catch specific exception
try:
...
except ValueError as e:
print(e)
# Multiple exceptions
try:
...
except ValueError as e:
...
except ZeroDivisionError as e:
...
# Catch any exception
try:
...
except Exception as e:
print(e)
# Finally (always runs)
try:
...
except ValueError:
...
finally:
# cleanup — always runs
# Raise an exception
raise ValueError("Invalid input!")
raise Exception("Something went wrong.")