Answer the question
In order to leave comments, you need to log in
Is there a need for a custom error hierarchy in Java?
Good afternoon!
I am developing small applications in Java. Your experience of creation of the exceptions interests. When should they be created? Do you organize them into a hierarchy of exceptions?
What's going on with me now:
public class Parameter {
...
public Parameter(String[] args) throws ParameterException {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM");
try {
startDate = dateFormat.parse( args[1] );
} catch (ParseException e) {
throw new ParameterException("Wrong month format.");
}
}
...
}
class ParameterException extends Exception {
public ParameterException(String message) {
super(message);
}
}
Answer the question
In order to leave comments, you need to log in
I often have to make my own hierarchy of exceptions. True, each exception carries a semantic load and should be handled differently. This hierarchy is especially useful when exceptions are thrown "to the top" and get into some kind of interceptor (as in Apache Camel, for example). Then, by the type of exception, you can easily understand what to do with it.
There are 2 opposing opinions on this matter, and both have their pros and cons.
In my opinion:
If you write a library/framework , then you can use your own exceptions. But only introduce new exception classes when you need them. Those. you don’t need to create an exception if you can get by with a system one, you don’t need to fence 200 types of errors, so that you can unwind the stack for hours, see who called what and write processing of dozens of different types of your errors in catch blocks. And in general, in this case, it is better to pass exceptions upstairs.
If you are writing an application , then do not create your own exceptions. Well, catch as much as possible so that the program does not fall on every sneeze, leave only the critical ones, with which you can’t live at all.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question