如何知道抛出哪个异常 [英] How to know which exception is thrown

查看:125
本文介绍了如何知道抛出哪个异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为我们的代码库进行审查,并且有很多这样的陈述:

  try 
{
doSomething()
} catch(异常e)
{

}

但我想要一种方式来知道doSomething()抛出的异常(在doSomething的实现中没有throw语句),所以我可以捕获该异常,而不是仅仅捕获异常一般来说,即使是findBug,它会发出警告 REC_CATCH_EXCEPTION



我应该提到,记录异常或将其打印到控制台不会帮助我,因为在这种情况下需要时间来重现导致此处异常的错误。 p>

谢谢

解决方案

如果没有 throws 语句 doSomething (例如 doSomething()抛出IOException ),将会发生的任何异常作为 RuntimeException 的实例。如果您想知道 doSomething 抛出的异常的确切类别,您可以随时尝试

  try {
doSomething();
} catch(RuntimeException e){
System.out.println(e.getClass()。getName());
}

知道在没有实际运行程序的情况下抛出哪些运行时异常是困难的。即使没有代码 doSomething()调用有一个显式抛出,核心java操作总是可以抛出 NullPointerException ArrayIndexOutOfBoundsException 等输入错误。以下是一些想法:




  • 手动挖掘。至少你会知道一些例外。

  • 使用反射来查找从 doSomething 可访问的任何throw语句。

  • 运行您的测试用例并记录上述抛出的异常。良好的测试将显示 doSomething 的呼叫者应该准备好的重要错误。

  • 转到那里把那个人放在那里第一个



无论如何,通常最好抓住尽可能具体的异常,因为你不知道当您尝试处理一个条款中的所有案例时,确切地 出错。


I'm doing a review for our codebase, and there are many statements like this:

try
{
   doSomething()
} catch (Exception e)
{

}

but I would like a way to know which exception is thrown by doSomething() (there's no throw statement in the implementation of doSomething) so i can catch that exception instead of just catching Exception in general, even with findBugs it gives a warning REC_CATCH_EXCEPTION.

I should mention that logging the exception or printing it to console will not help me because it takes time in this case to reproduce the error that causes the exception here.

Thanks

解决方案

If there's no throws statement in doSomething (e.g. doSomething() throws IOException), any exceptions that will occur will be an instance of RuntimeException. If you want to know the exact class of an exception thrown by doSomething, you can always try

try {
   doSomething();
} catch (RuntimeException e){
   System.out.println(e.getClass().getName());
}

Knowing which runtime exceptions can be thrown without actually running the program is difficult. Even if none of the code that doSomething() calls has an explicit throw, core java operations can always throw NullPointerException, ArrayIndexOutOfBoundsException, etc with the wrong input. Here are some ideas:

  • Dig through manually. At least you will know some of the exceptions.
  • Use reflection to find any throw statements accessible from doSomething.
  • Run your test cases and log the exceptions thrown like above. Good tests will reveal the important errors that callers of doSomething should be ready for.
  • Go to the people who put the catch there in the first place

In any case it's usually a good idea to catch exceptions that are as specific as possible, since you don't know exactly what went wrong when you try to deal with all cases in one clause.

这篇关于如何知道抛出哪个异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆