A
A
Andrew_Holmes2015-03-26 09:29:09
Java
Andrew_Holmes, 2015-03-26 09:29:09

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);
  }
}

As a result, it turns out that for each Class there is a ClassException corresponding to it. And all these Class Exceptions are arranged in the same way. To mine, it turns out not beautifully - a big heap of the same classes. And all are inherited from some MyApplicationException.
I heard the opinion that you should not create your own exceptions at all, they say the JDK already contains a large number of understandable exceptions.
I look forward to your advice and recommendations. Thank you!

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
alk, 2015-03-26
@Alexey_Kutepov

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.

B
bromzh, 2015-03-27
@bromzh

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 question

Ask a Question

731 491 924 answers to any question