When creating a user defined exception What is the best practice, should the exception be created as checked or unchecked ?
I know unchecked/runtime exceptions need not be handled in the code.
When creating a user defined exception What is the best practice, should the exception be created as checked or unchecked ?
I know unchecked/runtime exceptions need not be handled in the code.
If the exception is recoverable - it should be checked. If the exception is not recoverable and the program must halt - it should be unchecked.
A good summary about checked vs. unchecked exceptions can be found here.
Here is a snippet of my answer from another post:
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.
As the calling method may not handle RuntimeException, one needs to be careful while throwing RuntimeException.
Link to the complete answer : Extending Exception/RunTimeException in java?
Personally, I find the checked exception mechanism of Java to be burdensome.
While the distinction between recoverable and unrecoverable errors is valuable, there does not always seem to be a one-to-one mapping of a particular exception instance and the recoverability of its associated error, eg. not all IOExceptions are always recoverable.
The semantics that describe checked and unchecked exceptions are similarly murky. Even in the Java Platform libraries there does not always appear to be a consistent interpretation of these semantics. For example, exceptions generated in the JDBC platform library are checked; whereas exceptions generated in the JPA 2.0 API are unchecked.
More useful semantics may be the following:
when you wish to -force- the user of your API to respond to an exception that your library is generating, then define a checked exception. Usually this occurs when the exception must force the client to do something that is both different and important to do. This is a very valid use of the checked exception mechanism which becomes a part of the contract specified by your exported API.
when you wish to leave the user of your API free to decide for himself whether to handle your exception himself or to allow the exception to go unhandled, then throw an unchecked exception.
Especially if you are not creating an API to be exported in a library that you intend to distribute, the provided standard runtime exceptions are usually adequate for most purposes: