Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace a checked exception with a runtime exception?

Given that I basically want to eliminate checked exception usage and transform them to runtime exceptions, I would normally be doing something like this:

try {
    file.read();
} catch (IOException e){
    throw new RuntimeException(e); 
}

There are several disadvantages to doing this, but the one that irritates me the most is that my runtime exception would contain a nested stacktrace. Basically I would like to re-throw the "IOException" as a RuntimeException (or "IORuntimeException") with the original message and stacktrace, so I can avoid the useless nested stacktrace. The "fact" that I have re-thrown the exception somewhere in the middle seems like just useless noise to me.

Is this possible ? Is there any library that does this ?

like image 360
krosenvold Avatar asked Jun 08 '12 06:06

krosenvold


People also ask

Is runtime exception a checked exception?

In Java, exceptions under Error and RuntimeException classes are unchecked exceptions, everything else under throwable is checked. Consider the following Java program. It compiles fine, but it throws ArithmeticException when run. The compiler allows it to compile because ArithmeticException is an unchecked exception.

Can we extend checked exception instead runtime exception?

If you want to write a checked exception that is automatically enforced by the Handle or Declare Rule, you need to extend the Exception class. If you want to write a runtime exception, you need to extend the RuntimeException class.

Can runtime exception catch IOException?

Because IOException is a Checked Exception, which should be either handled or declared to be thrown. On contrary, RuntimeException is an Unchecked Exception.

Why we should not catch runtime exception?

Additionally, catching RuntimeException is considered as a bad practice. And, thus, throwing Generic Exceptions/Throwable would lead the developer to catch the exception at a later stage which would eventually lead to further code smells.


1 Answers

Project Lombok allows you to disable checked exceptions altogether.

like image 84
missingfaktor Avatar answered Sep 18 '22 14:09

missingfaktor