Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create checked/unchecked custom exceptions in Java?

Tags:

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.

like image 756
noob Avatar asked Aug 13 '11 09:08

noob


People also ask

How can we create custom checked and custom unchecked exception in Java?

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.

How do I create a custom unchecked exception?

We can create the custom unchecked exception by extending the RuntimeException in Java. Unchecked exceptions inherit from the Error class or the RuntimeException class.

Are custom exceptions checked or unchecked in Java?

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.

Does custom exceptions are checked or unchecked?

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.


1 Answers

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.

like image 93
GaryF Avatar answered Oct 14 '22 16:10

GaryF