Creating custom exception class in Java - Performance & Efficiency
When creating a custom exception class in Java, it's important to understand how the time cost grows when throwing or handling exceptions.
We want to see how the program's running time changes as exceptions are created or thrown.
Analyze the time complexity of the following code snippet.
public class MyException extends Exception {
public MyException(String message) {
super(message);
}
}
public void checkValue(int value) throws MyException {
if (value < 0) {
throw new MyException("Negative value not allowed");
}
}
This code defines a custom exception and throws it when a value is negative.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Creating and throwing the custom exception object.
- How many times: Each time the method is called with a negative value, the exception is created and thrown once.
Each call to checkValue either throws an exception or not, so the time depends on how many calls happen and how many throw exceptions.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | Up to 10 exception creations if all values are negative |
| 100 | Up to 100 exception creations if all values are negative |
| 1000 | Up to 1000 exception creations if all values are negative |
Pattern observation: The time grows linearly with the number of exceptions created and thrown.
Time Complexity: O(n)
This means the time grows in a straight line with the number of times the exception is thrown.
[X] Wrong: "Creating a custom exception class makes the program slower for all code, even when exceptions are not thrown."
[OK] Correct: Defining the class itself does not slow down normal code; only throwing exceptions takes extra time.
Understanding how exceptions affect time helps you write better error handling and shows you know how code performance changes in real situations.
"What if we changed the exception to be thrown inside a loop that runs n times? How would the time complexity change?"