Exception Handling
What Is Exception Handling?
Exception handling is the mechanism by which a program detects and responds to unexpected conditions or errors at runtime.
Proper use of exception constructs ensures robust programs that can recover from failures such as invalid input, missing resources, or logic errors.
Exception Handling Constructs
| Language | Try Block | Catch/Except | Finally |
|---|---|---|---|
| Python | try: |
except ExceptionType: |
finally: |
| Java | try {} |
catch (ExceptionType e) {} |
finally {} |
Try
The try block surrounds code that might fail. It attempts to execute normally, and if an exception occurs, control immediately transfers to the matching handler.
Except/Catch
The except (Python) or catch (Java) block specifies how to handle specific exception types thrown in the try block. You can chain multiple handlers to deal with different errors cleanly.
Finally
The finally block contains cleanup code-like closing files or releasing resources-that runs regardless of whether an exception was raised, ensuring your program doesn’t leak resources.
Example: Validating User Input
valid = False
while not valid:
user_input = input("Enter an integer between 1 and 10: ")
try:
value = int(user_input)
if 1 <= value <= 10:
valid = True # valid input
else:
print("Error: Number not in range.")
except ValueError:
print("Error: Invalid input; please enter a valid integer.")
print("You entered:", value)
import java.util.Scanner;
public class ValidateInput {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int value;
while (true) {
System.out.print("Enter an integer between 1 and 10: ");
String line = scanner.nextLine();
try {
value = Integer.parseInt(line);
if (value < 1 || value > 10) {
System.out.println("Error: Number not in range.");
} else {
break; // valid input
}
} catch (NumberFormatException e) {
System.out.println("Error: Invalid input; please enter a valid integer.");
}
}
System.out.println("You entered: " + value);
scanner.close();
}
}
Example: Handling File I/O Errors
try:
with open('data.txt') as file:
content = file.read()
except FileNotFoundError:
print("Error: data.txt not found.")
except Exception:
print("Error reading file.")
finally:
print("Execution completed.")
import java.io.FileReader;
import java.io.BufferedReader;
import java.io.IOException;
public class FileIOExceptionExample {
public static void main(String[] args) {
java.util.Scanner scanner = new java.util.Scanner(System.in);
try {
FileReader reader = new FileReader("data.txt");
BufferedReader br = new BufferedReader(reader);
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
br.close();
} catch (IOException e) {
System.out.println("Error reading file: " + e.getMessage());
} finally {
System.out.println("Execution completed.");
scanner.close();
}
}
}
Example: Handling Logical Errors (Divide by Zero)
try:
numerator = float(input("Enter numerator: "))
denominator = float(input("Enter denominator: "))
result = numerator / denominator
print("Result:", result)
except ZeroDivisionError:
print("Error: Cannot divide by zero.")
except ValueError:
print("Error: Please enter numeric values.")
except Exception as e:
print("Unexpected error:", e)
finally:
print("Execution completed.")
import java.util.Scanner;
public class DivideByZeroExample {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
try {
System.out.print("Enter numerator (int): ");
int a = scanner.nextInt();
System.out.print("Enter denominator (int): ");
int b = scanner.nextInt();
int result = a / b; // throws ArithmeticException if b == 0
System.out.println("Result: " + result);
} catch (ArithmeticException e) {
System.out.println("Error: Cannot divide by zero.");
} catch (java.util.InputMismatchException e) {
System.out.println("Error: Please enter integer values.");
} finally {
System.out.println("Execution completed.");
scanner.close();
}
}
}
Potential Failure Points
- Invalid Input: Non-numeric data when numbers expected.
- Resource Unavailability: Missing files, network timeouts, or database down.
- Logic Errors: Division by zero, null references, or out-of-bounds access.
Key Takeaways
- Exception handling prevents crashes by catching runtime errors.
- Python uses
try/except/else/finally; Java usestry/catch/finally. - Always handle potential failures: invalid input, missing resources, and logic faults.
- The
finallyblock runs regardless, ensuring cleanup actions execute.