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.

2 min read358 words

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")
BlockPurpose
tryCode that may raise an exception
exceptHandles specific exception types
elseRuns only if no exception was raised
finallyAlways runs — cleanup code

Common Built-in Exceptions

ExceptionCause
ValueErrorWrong data type (e.g., int("abc"))
ZeroDivisionErrorDivision/modulo by zero
IndexErrorList index out of range
KeyErrorDictionary key not found
FileNotFoundErrorFile 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

AdvantageExplanation
Graceful terminationProgram exits cleanly via finally block instead of crashing abruptly — cleanup code (e.g., closing files, releasing resources) always runs
User-friendly error messagesReplaces cryptic tracebacks with plain-language feedback like "Please enter a valid number"
Separation of concernsError-handling logic is separated from normal program logic — code stays clean and readable
Selective handlingDifferent except blocks handle specific errors differently, allowing precise and appropriate responses
Prevents cascading failuresCatching an exception early stops it from propagating and causing unrelated failures elsewhere
Debugging and loggingexcept Exception as e captures the full error message and stack trace for developers to diagnose issues
Resource safetyfinally ensures files, database connections, and network sockets are closed even when errors occur

Start typing to search all published objectives.