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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With