6

如果有一个带有多个 catch 块的 try-catch,有没有办法将异常重新抛出到下一个(不是底层)catch 子句?

例子:

try {

  // some exception can occur here

} catch (MyException ex) {

  // do something specific

  // rethrow ex to next catch

} catch (Exception ex) {

  // do logging stuff and other things to clean everything up
}

当 aMyException被抛出时,我想处理该异常的特定内容,但我想处理一般的异常(catch (Exception ex))。

我不想使用 finally 块,Java 7 Multi-catch 在这里也没有帮助。

任何如何处理这个问题的想法,我都想避免在每个 catch-block 中出现多余的东西。Exception只捕获然后instanceof用于我的特定东西会更好吗?

谢谢。

4

5 回答 5

4
public void doStuff()
{
   try
   {

     // some exception can occur here

   } catch (MyException ex){

     // do something specific

     cleanupAfterException(ex);

   } catch (Exception ex) {

     cleanupAfterException(ex);
   }
}

private void cleanupAfterException(Exception ex)
{
   //Do your thing!
}

我想这样的事情会做吗?

于 2013-10-09T08:24:31.660 回答
4

您可能想尝试这样的事情:

try
{

}
catch(Exception ex)
{
    if(ex instanceof MyException)
    {
        // Do your specific stuff.
    }
    // Handle your normal stuff.
}
于 2013-10-09T08:35:41.200 回答
1

你可以嵌套你的try语句:

try {
  try {

    // some exception can occur here

  } catch (MyException ex) {

    // do something specific

    // rethrow ex to next catch

  }
}  catch (Exception ex) {

  // do logging stuff and other things to clean everything up
}

虽然我担心这就是你所说的“ (不是底层) ”的意思?

于 2013-10-09T08:23:27.043 回答
0

您可以尝试多次尝试捕获:

try {

} catch(MyException ex) {
    try {

    } catch(Exception ex) {

    }
}
于 2013-10-09T08:21:47.283 回答
0

这肯定是功能的用途吗?

try {
    doStuff();
} catch ( MyException e ) {
    doMyExceptionStuff();
    doGeneralExceptionStuff();
    throw e;
} catch ( Exception e ) {
    doGeneralExceptionStuff();
}
于 2013-10-09T08:28:11.827 回答