Issue
I am programming a Java Servlet application which needs certain environment variables and JNDI definitions to be present. These are defined in server.xml
file. Using default values is not possible. So the program needs to throw a runtime (unchecked) exception. But which one? If none of the subclasses of java.lang.RuntimeException
is suitable, I guess we will need to create a new type.
Solution
You could use exceptions already defined, but I just usually implement my own, because I can always quickly recognize it when it is thrown. (It tells you more, just by having your project's classpath.)
public class MissingInitialContextException extends RuntimeException {
public MissingInitialContextException() {
}
public MissingInitialContextException(String message) {
super(message);
}
public MissingInitialContextException(String message, Throwable cause) {
super(message, cause);
}
public MissingInitialContextException(Throwable cause) {
super(cause);
}
public MissingInitialContextException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
}
You can auto generate classes like this in most IDE. (IDEA, after you created the class, ALT+ENTER and override methods from the RuntimeException class)
Why use custom exceptions.:
- You can use your IDE's find implementations and other search functions to locate usages
- In some frameworks, like in Spring Boot, you can decorate your exceptions with annotations and quickly define the response text and http error code.
- You can change the exception's implementation later.
- You can define automatic break on exception in your IDE for your custom exception, while if you would do this for a built in one, your debugger would stop in unexpected lines.
- You can avoid unintentionally catching other library's exceptions.
Answered By - szab.kel