B2.1.3
Describe how programs use common exception handling techniques
Exception handling prevents programs from crashing when errors occur by catching them and responding gracefully.
Exception handling prevents programs from crashing when errors occur by catching them and responding gracefully.
try:
x = int(input("Enter a number: "))
result = 10 / x
except ValueError:
print("Invalid input — not a number")
except ZeroDivisionError:
print("Cannot divide by zero")
else:
print(f"Result: {result}")
finally:
print("Done")
| Block | Purpose |
|---|---|
try | Code that may raise an exception |
except | Handles specific exception types |
else | Runs only if no exception was raised |
finally | Always runs — cleanup code |
Common Built-in Exceptions
| Exception | Cause |
|---|---|
ValueError | Wrong data type (e.g., int("abc")) |
ZeroDivisionError | Division/modulo by zero |
IndexError | List index out of range |
KeyError | Dictionary key not found |
FileNotFoundError | File does not exist |
Raising custom exceptions
Use raise ExceptionType("message") to trigger exceptions manually.
age = -1
if age < 0:
raise ValueError("Age cannot be negative")
Catching Any Exception
except Exception as e catches any exception and stores it in variable e, allowing you to inspect or log the error message:
try:
x = int(input("Enter a number: "))
except Exception as e:
print(f"Error occurred: {e}")
Advantages of Exception Handling
| Advantage | Explanation |
|---|---|
| Graceful termination | Program exits cleanly via finally block instead of crashing abruptly — cleanup code (e.g., closing files, releasing resources) always runs |
| User-friendly error messages | Replaces cryptic tracebacks with plain-language feedback like "Please enter a valid number" |
| Separation of concerns | Error-handling logic is separated from normal program logic — code stays clean and readable |
| Selective handling | Different except blocks handle specific errors differently, allowing precise and appropriate responses |
| Prevents cascading failures | Catching an exception early stops it from propagating and causing unrelated failures elsewhere |
| Debugging and logging | except Exception as e captures the full error message and stack trace for developers to diagnose issues |
| Resource safety | finally ensures files, database connections, and network sockets are closed even when errors occur |