Search code examples
javaexceptionlibrary-design

Is catch(Exception) viable for convenience methods if there is an overload that allows proper handling?


I am developing a library for working with files and want to make it as easy to use (i.e. not having to worry about exceptions), but also as complete as possible (i.e. allow for proper exception handling).

To achieve this, I expose two methods. One that allows for normal catching of exceptions:

public void saveChecked() throws IOException, IllegalArgumentException {
    // Possibly throw an IOException or IllegalArgumentException
}

...and one that handles all exceptions using a generic Consumer<Exception>:

public void save(Consumer<Exception> handler) {
    try {
        saveChecked();
    } catch (Exception exception) {
        handler.accept(exception);
    }
}

The intention behind this is, that, if you don't need to differentiate between exceptions and just want to do one simple thing when an exception is thrown (e.g. print the stack trace, show a popup), you can just use the second version instead of having to write out a try-catch block (and making one-liners impossible).

Is this still bad practice even though the API does expose a method which allows proper exception handling for those that need it?


Solution

  • I am developing a library for working with files and want to make it as easy to use (i.e. not having to worry about exceptions), but also as complete as possible (i.e. allow for proper exception handling).

    It's java. Exceptions are part of the language. Reinventing the exception system is mostly just going to lead to a bizarre library that doesn't fit in with the rest of java.

    do one simple thing when an exception is thrown (e.g. print the stack trace, show a popup)

    psv main is allowed to be declared as throws Exception. More generally, if you want to handle all exceptions in the same way, let the exception bubble all the way to the top, and register an exception handler e.g. via Thread.setDefaultUncaughtExceptionHandler.

    If you just hate checked exceptions, you probably shouldn't be using java. However, if you somehow must go against the grain, there's always UncheckedIOException that you can throw, which makes that whole 'bubble up to the top, register an uncaught exception handler' a little bit easier.

    Is this still bad practice

    Yes. Writing non-idiomatic java is bad practice.