Checked vs unchecked exceptions in Java - Performance Comparison
We want to understand how the time cost changes when handling checked and unchecked exceptions in Java.
How does the program's running time grow when exceptions are checked or unchecked?
Analyze the time complexity of the following code snippet.
public void process(int[] data) {
for (int i = 0; i < data.length; i++) {
try {
if (data[i] == 0) throw new Exception("Checked");
int result = 10 / data[i];
} catch (Exception e) {
System.out.println("Handled checked exception");
}
}
}
This code loops through an array and throws a checked exception if an element is zero, then handles it inside the loop.
- Primary operation: Looping through the array elements once.
- How many times: Exactly once per element, so n times where n is array length.
Each element causes one try-catch check and possibly an exception throw and catch.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 loop checks and exception handling attempts |
| 100 | About 100 loop checks and exception handling attempts |
| 1000 | About 1000 loop checks and exception handling attempts |
Pattern observation: The work grows directly with the number of elements, so doubling input doubles work.
Time Complexity: O(n)
This means the time to run grows in a straight line with the number of elements processed.
[X] Wrong: "Throwing exceptions inside a loop makes the program run in quadratic time."
[OK] Correct: Each exception is handled immediately and does not cause nested loops or repeated work, so time grows linearly, not squared.
Understanding how exceptions affect time helps you write clear, efficient code and explain your choices confidently in interviews.
"What if we moved the try-catch block outside the loop? How would the time complexity change?"