🌱BeginnerWorking with Python
Error Handling (try / except)
Catching and handling exceptions with try, except, else, and finally.
Overview
When something goes wrong at runtime a file isn't found, a user types text where a number was expected, a network request fails Python raises an exception. If the exception is unhandled, the program crashes and prints a traceback. Exception handling lets your program detect and recover from these situations gracefully.
The basic structure is try/except: code that might fail goes in the try block; the except block runs if a specific exception is raised. You can catch multiple exception types, inspect the exception message, and even define your own exception classes.
Two optional clauses complete the structure:
- **else** runs if the try block completed without raising an exception
- **finally** runs regardless of whether an exception was raised ideal for cleanup (closing files, releasing resources)
Python has a rich exception hierarchy. Common exceptions: ValueError (wrong value type), TypeError (wrong type), KeyError (missing dict key), IndexError (list index out of bounds), FileNotFoundError, ZeroDivisionError.
Key Points
- •try: block contains code that might fail; except ExceptionType: handles that error
- •catch multiple: `except (ValueError, TypeError):` or multiple except blocks
- •except Exception as e: stores the exception object; print(e) shows the message
- •else: block runs only if no exception was raised good for code that should run only on success
- •finally: block always runs used for cleanup (close files, release locks)
- •raise re-raises the current exception; `raise ValueError("message")` raises a new one
- •Catch specific exceptions, not bare except: broad catches hide bugs
Examples
Basic try/except
# Without error handling crashes if input is not a number
# age = int(input("Age: ")) # could raise ValueError
# With error handling
try:
age = int("not-a-number")
except ValueError as e:
print(f"Invalid input: {e}")
age = 0
print(f"Age: {age}") # Age: 0Multiple except clauses and else/finally
def safe_divide(a, b):
try:
result = a / b
except ZeroDivisionError:
print("Cannot divide by zero!")
return None
except TypeError as e:
print(f"Type error: {e}")
return None
else:
print("Division successful.")
return result
finally:
print("safe_divide() finished.") # always runs
print(safe_divide(10, 2)) # 5.0 + success message
print(safe_divide(10, 0)) # ZeroDivisionError handledRaising exceptions
def set_age(age):
if not isinstance(age, int):
raise TypeError(f"age must be int, got {type(age).__name__}")
if age < 0 or age > 150:
raise ValueError(f"age must be 0-150, got {age}")
return age
try:
set_age(-5)
except ValueError as e:
print(f"ValueError: {e}")Common Mistakes
- Using bare `except:` without an exception type catches everything including KeyboardInterrupt and SystemExit, making it impossible to stop the program
- Catching Exception too broadly and silently swallowing errors: always at least log the error
- Putting too much code in try blocks only wrap the specific line(s) that might fail
Note
Think of exceptions as signals for exceptional situations, not routine control flow. If you expect a condition to happen frequently (like a user entering bad data in a loop), check with if/else rather than try/except for clarity.
Exercises
Write Python code to solve each exercise. Run it in your browser and check your output.
Loading editor…
Completed: 0 / 5 exercises
Knowledge Check
Question 1 of 4