【问题标题】:Continue Execution even after program catches exception即使在程序捕获异常后继续执行
【发布时间】:2013-11-11 19:50:07
【问题描述】:

这是一个示例:

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
      }

     }
    }

当情况是这样的时候。

当调用 Method2 中的 catch 块时,我希望程序继续执行并返回到 Method 1 中的 else 块。我该如何实现呢?

感谢您的帮助。

【问题讨论】:

    标签: java exception-handling


    【解决方案1】:

    简单地将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
    }
    

    【讨论】:

    • 感谢您的回复。但它最终将如何执行 else 块中的代码。你的逻辑很完美我只是很难理解它最终会如何进入 else 块
    • @Ashish 我给出的代码只会优雅地处理异常。它不会执行 else 块中的代码。 if 和 else 块是互斥的,即一次只能执行一个。如果您有一些代码要在 if 块中的异常和正常 else 块执行的情况下执行,则将 else 块的代码移动到方法中。并从 if 块中的 catch 块和普通 else 块中调用该方法。
    【解决方案2】:

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

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

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

    【讨论】:

    • 谢谢,但我无法找出将在 try 中抛出的最具体的异常。如果没有特定的例外,执行会更高,并且永远不会调用 method3
    • 对不起,我不明白您所说的“执行会更高并且永远不会调用 method3”是什么意思。在上述情况下,如果曾经调用过异常并将其移入 Catch 块,则将自动调用方法 3。您不必有特定的异常,对不起,这是我的错误,但是如果您遇到不想在出现异常时调用 Method3() 的情况,则需要另一个 Catch Block
    • 不,我不这样做,只是因为如果在方法 2 的 try 块期间发生意外错误,程序仍然会运行 method3... 这可以用于非常具体的示例,其中 method3是一种“防撞”方法,在这种情况下,请确保这个想法可行。但是,如果你能避免它,请这样做。附带说明:如果我的回答解决了您的问题,请接受!
    【解决方案3】:

    你需要一个双 if 代替。

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-31
      相关资源
      最近更新 更多