Using runtime exception
In practice, extending Exception (checked exceptions) can sometimes violate the Closed Principle and extending RuntimeException (unchecked exceptions) is often preferred comes down to flexibility, maintainability, and the impact on client code.
Checked exception forces clients to modify code
When you define a new checked exception, any method that uses code throwing this exception must either:
- catch it (
try-catch), or - declare it (
throws)
That means existing code must be modified even if the exception is never expected to occur.
Unchecked exception
- Doesn’t force changes in client code
- Can be introduced without breaking existing interfaces
- Supports more flexible and decoupled design
public class MyCustomException extends RuntimeException { }
public class MyService {
public void doSomething() {
throw new MyRuntimeException();
}
}Now:
- The caller can catch it, but is not forced to
- Existing code using
doSomething()doesn’t need to change — keeping it closed for modification
Recommendations
- Use checked exceptions only when the caller can and should do something to recover (e.g., file not found, user input error)
- Use runtime exceptions when the error is unrecoverable or should bubble up (e.g., illegal state, programming errors), and when you want to preserve the Open/Closed Principle
Back to parent page: Java Standard Edition (Java SE) and Java Programming
Web_and_App_Development Programming_Languages Java Exception Exception_Best_Practice