Is it wrong to use a run-time exception with an internal, checked exception?

Is this a 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(); } 

Suppose there is no way to gracefully recover from a checked exception.

+4
source share
3 answers

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

This approach becomes convenient when foo(File file) is an implementation of an interface method or an override of a superclass method that does not throw a checked exception. This situation forces you to deal with an exception from within or to transfer it to an exception that has not passed the test.

However, the problem is that subclasses of RuntimeException should signal programming errors; IOException , on the other hand, does not signal a software error, so wrapping it in a RuntimeException to bypass Java compiler checks is wrong.

+5
source

Java runtime uses UncheckedIOException for this kind of situation.

I would say that it is bad practice to define new types of unchecked exceptions and to exit the library because it causes abstractions to flow. If you intend to throw the checked exception as an exception, find the appropriate subclass of RuntimeException in the main Java runtime.

+1
source

Checked exceptions are problematic - I heard they are best described as a “Failed Experiment”.

Runtime exceptions are a pretty good way to handle sticky situations. For example, you often have a large, high-level thread that is expected to be run by Forever. In this stream (inside different methods) there can be 30 places that are read from the database or interact with some other unstable source.

If this data source fails, you always want to process it in the same way - reconnect, and then restart the main loop.

This is very easy to handle in a high-level stream, but if each object processes it itself, it distributes horrible error checking code throughout the project.

So, the answer: feel free to wrap your flag in an excluded exception from the runtime if there is nothing useful at this level - and I would advise NEVER throw a checked exception if there is something that caller SHOULD handle immediately (which almost never it happens - most problems can be handled at a higher level).

By the way, I do this a lot and almost never use new exceptions - you can reuse existing ones if you have no reason to distinguish exceptions at a higher level.

-one
source

All Articles