Reputation: 96491
Is it possible to create my own unchecked exception in Java?
Basically, I'd like to
MyUncheckedException
throws
Upvotes: 23
Views: 20544
Reputation: 6590
I'll leave an example here, just in case:
public class MyCustomException extends RuntimeException {
public MyCustomException(String message) {
super(message);
}
}
Upvotes: 1
Reputation: 1475
YES. According to Effective Java -
While the Java Language Specification does not require it, there is a strong convention that errors are reserved for use by the JVM to indicate resource deficiencies, invariant failures, or other conditions that make it impossible to continue execution. Given the almost universal acceptance of this convention, it’s best not to implement any new Error subclasses. Therefore, all of the unchecked throwables you implement should subclass RuntimeException (directly or indirectly).
Below usage of unchecked exception is recommended :-
About documenting unchecked exception -
Use the Javadoc @throws tag to document each unchecked exception that a method can throw, but do not use the throws keyword to include unchecked exceptions in the method declaration.
Upvotes: 0
Reputation: 726987
Yes - derive it from RuntimeException
Make sure that you do it for the right reason: as a rule, runtime exceptions indicate programming errors, rather than errors that a program could potentially react to in some meaningful way.
Upvotes: 5
Reputation: 80194
Yes. Extend MyUncheckedException
from RuntimeException
. However, below is the guideline from documentation
Generally speaking, do not throw a RuntimeException or create a subclass of RuntimeException simply because you don't want to be bothered with specifying the exceptions your methods can throw.
Here's the bottom line guideline: If a client can reasonably be expected to recover from an exception, make it a checked exception. If a client cannot do anything to recover from the exception, make it an unchecked exception.
Upvotes: 36