Runtime exception handling in Java

I have the following code snippet

 try{//do something
     }
  catch (Exception e) {
        log.error(e, e);
        if (e instanceof RuntimeException) {
            throw (RuntimeException) e;
        } else {
            throw new RuntimeException(e);
        }
    }

findbugs stataic analysis tool throws this warning on it

instanceof always returns true for all nonnull values ​​in methodX, since all RuntimeException are instances of RuntimeException

what I don't understand is that its Exception is caught, not a RuntimeException, so why is this a warning?

+3
source share
4 answers

You can also try the following code. It will be better to read and support.

try{//do something
}
catch (RuntimeException e) {
    throw e;
} 
catch (Exception e) {
    throw new RuntimeException(e);
}
+4
source

, // do something , , try-, ( RuntimeException).

+6

There are probably no methods that do not throw a RuntimeException on the try part. Therefore, you can use the construct

catch(RuntimeException e)
{
 //Do something
}
+2
source

Try http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/base/Throwables.html#propagate%28java.lang.Throwable%29 . He does exactly what you want. Today I made a replacement for the same reason (warningbugs warning), also looked at the source of this method.

0
source

All Articles