M
M
MrShaggy2017-02-03 11:10:28
Java
MrShaggy, 2017-02-03 11:10:28

Java Exceptions. What to do with a large number of exceptions?

Greetings!
Let's say I have an application with console I/O. The user can enter commands, and the program, in case of some incorrect actions of the user, suggests a solution to this problem (checked exceptions).
Let the user interact with the console and call the method:

public String foo() throws BlaBlaException, BlaFooException, FooFooExcpetion, InfinityException { // и так может очень много
    //bla bla
    throw new BlaBlaExcpetion();
    //. . . 
    // bla bla
    throw new InfinityException();
}

Imagine that all these exceptions must be handled by the user himself. That is, there will eventually be a level that will catch exceptions and help the user.
It can be seen from the method example that 4 exceptions are thrown here (throws ...) , and this already hurts the programmer's eyes a little. And if you imagine that these exceptions will be not 4, but 10! And there will be 4-5 levels of transferring! This already smacks of some kind of shit code ... Or am I wrong?
Is this normal practice or is there another way to do this?
PS I know that you can make one ancestor for all these exceptions, put a string into it with an explanation of the problem and rethrow it. But then what? I will have to consider all cases through switch ...

Answer the question

In order to leave comments, you need to log in

2 answer(s)
F
Fat Lorrie, 2017-02-03
@DrNefario

At different logical levels, it is possible (and necessary) to re-throw more general types of exceptions (with a link to the original inside), if there is no way to process them in place. For example, TooLongNameExceptionand NegativePriceExceptionwill become higher somewhere ModelValidationException, i.e. there, it is enough for you to know that the model is a curve, regardless of the reason for this.
Maybe the example is not the most successful, because inheritance would be suitable here. In general, a large list of exceptions is an indirect sign that the method does too much (S - SOLID).

T
tapokshot, 2017-02-03
@tapokshot

So process them immediately in this method).

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question