简体   繁体   中英

Throw IOException instead of Exception

I have method1() which is called from lots of other methods throughout the code. This is the signature of the method:

 public void method1(final Properties properties) throws IOException {}

All methods calling this method also throw IOException.

The actual code in method1() changed, so now instead of IOException it throws some other exceptions that extend Exception and not IOException anymore.

I don't want to change the signature of all methods calling method1().

Is it ok to create IOException and still throw IOException from method1() and hence the methods calling method1()?

Something like below:

 Try {
  // code
 } catch (Exception e) {
   throw new IOException(e.getCause());
 }

No , you should not do this, because you will confuse every other developer reading your code or reading stacktraces.

From the software-design point of view, the error happened a lot earlier. If your code is like an API and used by others, you may better have used Custom-Exceptions and wrapped the IOException as root-cause.

If you have the complete source, you should refactor the source and add another exception signature.

You need to save the original exception as the cause, so you're not losing the original message or stacktrace. Calling e.getCause() in your code example is skipping over the exception that you caught and getting its cause, which is suspicious-looking.

Also it would be better to specify the particular exceptions that the method catches, rather than using a catch-all Exception type. Catching Exception would result in things like NullPointerExceptions getting caught that were not trapped before.

The best thing to do here is change the exceptions thrown by your method to a custom type that doesn't let the implementation details bleed through to the callers. Your method signature should change to

public void method1(final Properties properties) throws SomeCustomException {
    try {
        .... // do whatever
    } catch (AException | BException | CException e) {
        throw new SomeCustomException(e);
    }
}

This will work technically.

However, catching Exception or Throwable is almost everytime a bad idea (as is throwing them), because you will also catch all other Exceptions, besides RuntimeExceptions .

If you can change the code of all calling classes (ie you are not developing a framework/library), you should do so. Because I assume you meant method1() throws a more specific type now.

You may also think about throwing a Subtype of RuntimeException which does not need to be catched, and is a good idea for errors that can't be corrected (eg a bad configuration). (see Clean Code by Robert Martin)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM