When I create my own exceptions, is it possible to mark them as being checked/unchecked? (using some annotation, maybe?) Or, is extending Exception/RuntimeException the only way of doing it?
Thanks.
Custom Checked and Custom UncheckedIf you want to write a checked exception that is automatically enforced by the Handle or Declare Rule, you need to extend the Exception class. If you want to write a runtime exception, you need to extend the RuntimeException class.
We can create the custom unchecked exception by extending the RuntimeException in Java. Unchecked exceptions inherit from the Error class or the RuntimeException class.
All exceptions in Java are checked. This means that must be explicitly catched in a try-catch block. Runtime exceptions need not be caught (java.
The custom exception should extends RuntimeException if you want to make it unchecked else extend it with Exception. With unchecked exceptions calling code method is not required to declare in its throws clause any subclasses of RuntimeException that might be thrown during the execution of the method but not caught.
The only way of doing it is to extend Exception (or a subclass thereof) for a checked exception, and extending RuntimeException (or a subclass thereof) for an unchecked exception.
Given how lightweight it is to do that, and the benefits you get from extending those classes, I don't think that's too onerous.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With