Throw a long list of exceptions, and also throw an exception Exception vs throw?

I have an application that uses two API methods. Both of these methods throw more than five exceptions. So, if I just add a throws declaration, then it will become a list of more than ten. (My method cannot handle any of the ten exceptions)

I read that throwing a long list of exceptions is bad practice. Also throwing (umbrella) exception is bad practice. So what should I do?

  • Add a catch try block and enter and exit the catch block?
  • Create your own exception class, wrap all exceptions, and throw a custom exception?
  • Add a throw ad for all exceptions?
  • Throw Exception?
  • Add a try catch block and throw a RuntimeException in the catch block? (Current approach)

Edit: Added selection 5.

+6
java exception-handling
source share
7 answers

"2. Create your own exception class," but not for everyone. Complete exceptions in logical groups. For example, you can have an XmlWritingException , PaymentGatewayException and DataAccessException that throw different exceptions depending on the scenario.

It is even possible (and preferably) to wrap the same exception in a different shell. For example, you can wrap an IOException in a PaymentGatewayException if the payment was unsuccessful due to a communication problem, but in an XmlWritingException if it failed during some xml I / O. All of these examples are hypothetical, but you get the idea.

The most important thing is to establish the original exception as the cause of the new one so that it is not lost.

Update: In fact, option 5 is great if you cannot expect the client to recover normally from the exception. Even better, the custom exceptions you create can be extended by a RuntimeException . What spring does, for example, wrap all data-related exceptions in a DataAccessException .

+2
source share

If the calling elements of your code may possibly handle some of the exceptions, then I will declare your method as throwing them and passing them. If you have no hope of this, I will create my own exception that extends (does not check) the RuntimeException and throws your custom exception with the actual exception associated with it.

As a rule, I put off decisions on entering politics as high as possible. The exit (if you want to exit the process) should always be delayed in the code so that you can unit test it.

In general, my philosophy around exceptions is:

  • If the error is a "business logic problem" and the caller can handle it (by choosing an alternative logic or asking the user what to do), then throw the user checked exception. Example: Throw a UserDoesNotExistException to indicate that the username does not exist in the data system, and let the next layer ask the user to create an account. While you are on it, you might think about whether the code can be structured so that an exception is not actually required.
  • Exceptions that are unexpected should be exceptions (not flagged). You want them to skip your code pretty much unchanged to the maximum possible point (the stack stream is small), where they can be processed as exceptional conditions (by throwing an error page, registering an error, sending an alert to the operator, introspecting the state of the system, and including, with an error message, etc.). Do not trap, wrap, or destroy IF you can add factual information that can be used to diagnose the problem.
+2
source share

Generally speaking, if your method cannot handle exceptions, it must re-throw them or add them to the throw section. Hiding exceptions in a catch block seems to be the worst choice.

+1
source share

As always, it depends.

  • Is this your API? If so, change it and let it eliminate fewer exceptions. Handle them in some way.

  • Try to make your program as long as possible. This means that if there is no configuration file, do not throw an IOException and exit. Hardcode is some default configuration. If you are not connected to the Internet, show the message and do not exit.

  • Sometimes you can return something special (variations on the special case pattern and the Null Object pattern), and then throw an exception.

  • Consider using the Observer pattern for some exceptional cases. Do not throw an exception, but notify someone who should show a message or do something else.

  • Do not hide any of them. Record all exceptions.

+1
source share

If your API is called Foo, I would throw a FooAPIException. Remember to include the source exception in the FooAPIException. When registering and throwing a FooAPIException, the stack trace of the original exception is also displayed.

For example:

 public class FooAPIException extends Exception { private Exception root; public FooAPIException (Exception e) { super(e.getMessage(),e.getErrorCode()); root = e; } public Exception getRoot () { return root; } // Exception ================================================================ public String toString () { StringBuffer sb = new StringBuffer(); sb.append("["); sb.append(getErrorCode()); sb.append("]["); sb.append(getMessage()); sb.append("]\n"); sb.append("ROOT CAUSE:"); Writer write = new StringWriter(); PrintWriter pw = new PrintWriter(write); e.printStackTrace(pw); pw.close(); try { write.close(); } catch (IOException ioe) {/**/} root = write.toString(); sb.append(write); return sb.toString(); } } 

And then wrap the API:

 public class FooAPI { public static method (String params) throws FooAPIException { try { RealFooAPI.method(params) } catch (Exception e) { throw new FooAPIException(e); } } } 
+1
source share

You can wrap exceptions with a custom custom exception.

However, the problem with this is that by hiding what caused the exception (let's say it was an IOException ), you are hiding information that would theoretically allow a higher level of code to catch this exception specifically and deal with it. In this case, you are no better than throwing a RuntimeException , so you can also wrap them with a RuntimeException .

I would still leave those that you could imagine a reasonable subscriber who wants to specifically catch and declare them on purpose or wrap them in groups.

0
source share

If you do not handle the exception in this method, it is best to wrap them in one or more custom exceptions and throw them away so you can handle them at the top level.

You can also throw an exception that is thrown from the exception (RuntimeException extension) and wrap the thrown exceptions in your own exception for execution.

0
source share

All Articles