Handling Runtime exception in Java

和自甴很熟 提交于 2019-12-23 20:25:15

问题


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 ?


回答1:


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);
}



回答2:


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).




回答3:


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

catch(RuntimeException e)
{
 //Do something
}



回答4:


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.



来源:https://stackoverflow.com/questions/10717585/handling-runtime-exception-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!