try/catch in Java and try/except in Python allow a program to detect and handle an exception instead of terminating immediately. The program attempts the code in the try block; if an exception occurs, control transfers to a compatible handler.
An exception is an event that interrupts the program's normal flow, such as division by zero, invalid user input, or accessing a nonexistent file. Exception handling is part of B2.1 Programming fundamentals because it makes programs more robust.
The mechanism follows these steps:
- The statements in
tryexecute in order. - If no exception occurs, the handlers are skipped.
- If an exception occurs, the remaining statements in
tryare skipped. - The language searches for a handler matching the exception type.
- The matching handler executes. If none matches, the exception propagates and may terminate the program.
- An optional
finallyblock executes whether or not an exception occurred, making it useful for cleanup.
| Java | Python |
|---|---|
Uses try and catch | Uses try and except |
Specifies a type such as ArithmeticException | Specifies a type such as ZeroDivisionError |
Can use multiple catch blocks | Can use multiple except blocks |
Uses finally for cleanup | Uses finally for cleanup |
try {
int result = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero");
}
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero")
In both examples, division raises an exception, so the output statement in the matching handler runs. Execution can then continue after the exception-handling structure.
A common misconception is that exception handling prevents errors. It does not prevent the exception; it defines how the program responds when one occurs. In an IB response, trace the control flow precisely, identify the exception type, and explain why the corresponding handler executes.