Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it bad practice to throw a runtime exception with an inner, checked exception? [duplicate]

Tags:

java

exception

is this bad practice?

public String foo(File file) {
    StringBuilder sb = new StringBuilder();
    try(
            BufferedInputStream bis =
                    new BufferedInputStream(
                            new FileInputStream(file))
    ) {
        for(int c = bis.read(); c != -1; c = bis.read())
            sb.append((char) c);
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }
    return sb.toString();
}

Assume that there is no way to gracefully recover from the checked exception.

like image 921
Joseph Nields Avatar asked Aug 06 '15 16:08

Joseph Nields


2 Answers

This is not ideal, but there are situations when there is no other workaround.

This approach becomes convenient when foo(File file) is an implementation of an interface method or an override of a superclass method which does not declare the checked exception. This situation forces you deal with the exception internally, or wrap it in a non-checked exception.

The problem, however, is that subclasses of RuntimeException are supposed to signal programming errors; IOException, on the other hand, does not signal a programming error, so wrapping it in RuntimeException in order to circumvent Java compiler's checks is wrong.

like image 173
Sergey Kalinichenko Avatar answered Sep 27 '22 22:09

Sergey Kalinichenko


The Java runtime uses UncheckedIOException for this kind of situation.

I would argue that it is a bad practice to define new types of unchecked exceptions and let them escape from a library, because it causes leaky abstractions. If you are going to rethrow a checked exception as an unchecked exception, find a suitable RuntimeException subclass in the core Java runtime.

like image 44
erickson Avatar answered Sep 27 '22 22:09

erickson