5

I have the following piece of code

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

the findbugs stataic analysis tool throws this warning on it

instanceof will always return true for all nonnull values in methodX, since all RuntimeException are instances of RuntimeException

what i dont understand is that its Exception which is being caught and not the RuntimeException, so why this warning ?

asked May 23, 2012 at 9:58
0

4 Answers 4

6

Perhaps, the // do something code does not throw any checked exception, so the only exceptions you can get in your try-block are unchecked ones (subclassing RuntimeException).

answered May 23, 2012 at 10:00
Sign up to request clarification or add additional context in comments.

Comments

4

You could also try following code. This will be better to read and maintain.

try{//do something
}
catch (RuntimeException e) {
 throw e;
} 
catch (Exception e) {
 throw new RuntimeException(e);
}
answered May 23, 2012 at 10:08

Comments

2

Probably there is no methods that throws not RuntimeException in "try" part. Therefore, you can use construction

catch(RuntimeException e)
{
 //Do something
}
answered May 23, 2012 at 10:04

Comments

0

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

answered Oct 3, 2012 at 15:18

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.