Java 即使在程序捕获异常后继续执行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19712745/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 19:37:27  来源:igfitidea点击:

Continue Execution even after program catches exception

javaexception-handling

提问by Ashish

here is a sample:

这是一个示例:

class A{

    method1(){
     int result = //do something
     if(result > 1){
      method2();
     } else{
       // do something more
     }
    }

    method2(){
     try{
       // do something
     } catch(Exception e){
       //throw a message
      }

     }
    }

when situation is something like this.

当情况是这样的。

When the catch block inside Method2 is called, I want the program to continue execution and move back to the else block inside Method 1. How can I achieve this?

当 Method2 中的 catch 块被调用时,我希望程序继续执行并移回方法 1 中的 else 块。我怎样才能做到这一点?

Thanks for any help.

谢谢你的帮助。

采纳答案by XQEWR

I think what you are looking for is something like this:

我认为你正在寻找的是这样的:

class A{

method1(){
 int result = //do something
 if(result > 1){
   method2();
 }else{
   method3(); 
 }
}

method2(){
   try{
   // do something
   } catch(Exception e){ // If left at all exceptions, any error will call Method3()
     //throw a message
     //Move to call method3()
     method3();
   }
 }

 method3(){
  //What you origianlly wanted to do inside the else block

 }
}

}

In this situation, the program will call Method3 if it moves into the catch block inside method 2. While inside Method1, the else block also calls method3. This will imitate the program 'moving back' to the else block from the catch block

在这种情况下,如果程序移动到方法 2 中的 catch 块,程序将调用 Method3。而在 Method1 中,else 块也调用 method3。这将模仿程序从 catch 块“移回”到 else 块

回答by Juned Ahsan

Simply encapsulate the call of method2in a try-catchblock. Catching the exception will not allow the unhandled exception to be thrown. Do something like this:

简单地将 的调用封装method2在一个try-catch块中。捕获异常将不允许抛出未处理的异常。做这样的事情:

if(result > 1){
    try {
         method2();
     } catch(Exception e) { //better add specific exception thrwon from method2
         // handling the exception gracefully
     }
   } else{
       // do something more
}

回答by Voidpaw

You need a double ifinstead.

你需要一个双if

method1()
{
    if(result > 1)
    {
        if(method2()) { execute code }
        else { what you wanted to do in the other code }
    }
}

and ofc let method 2 return something (in this case I let it return bool for easy check)

和 ofc 让方法 2 返回一些东西(在这种情况下,我让它返回 bool 以便于检查)