Exception Handling in Programs
Why Exception Handling Is Needed
- Programs may fail due to:
- Unexpected inputs (e.g., dividing by zero, invalid user entry).
- Resource unavailability (e.g., file not found, network failure).
- Logic errors (e.g., null references, array index out of bounds).
- Without exception handling, programs may crash abruptly.
Always predict where code could fail and handle it gracefully.
Relying only on testing: unexpected errors can still occur at runtime.
Exception Handling Constructs
Try / Catch (Java)
- Code that might fail goes inside try.
- Errors are caught in catch.
try {
int x = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero");
}
Catch specific exceptions instead of using a generic Exception.
Putting all code in try block → makes debugging harder.
Try / Except (Python)
try:
x = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero")Use multiple except blocks to handle different error types.
3. Finally Block (Java)
- Runs no matter what (error or no error).
- Useful for cleanup tasks (closing files, releasing resources).
try {
FileReader f = new FileReader("data.txt");
} catch (IOException e) {
System.out.println("File not found");
} finally {
System.out.println("End of program");
}Use finally to ensure important tasks (like closing a file) always run.
Forgetting cleanup code → resource leaks.
Benefits of Exception Handling
- Prevents program crashes.
- Provides user-friendly error messages.
- Makes debugging and maintenance easier.
- Ensures resources are safely released.
Think of exception handling as a safety net for your program.
Using exception handling as a replacement for proper input validation.