2013-10-31 155 views
2

即使这里是一个示例:继续执行程序捕获异常

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块被调用时,我希望程序继续执行并返回到方法1中的else块。我该如何实现这个功能?

感谢您的任何帮助。

回答

1

我想你在找什么是这样的:

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块也调用method3。这将模仿程序'移回'到catch块的else块

+0

谢谢,但是我无法弄清楚最具体的例外情况,它会在尝试中抛出。没有特定的例外,执行会变得更高,永远不会调用方法3 – Ashish

+0

对不起,我不明白你的意思是“执行会更高,永远不会调用method3”。在上面的情况中,如果有一个例外被调用并且它移动到Catch Block中,则方法3将自动被调用。你不必有特定的异常,对不起,这是我的错误,但是如果你有什么情况你不想调用Method3(),当有异常时,你将需要另一个Catch Block – XQEWR

+0

最后一个问题:我们认为这是一个很好的做法吗? – Ashish

4

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

感谢您的回应。但它将如何最终执行else块中的代码。你的逻辑是完美的我只是很难理解它会如何最终在其他块 – Ashish

+0

@Ashish我给出的代码将只是优雅地处理异常。它不会执行else块中的代码。如果和其他块互斥,即一次只能执行一个块。如果你有一些代码在if block和normal else block执行时都要执行,那么在方法中移动else块的代码。并从if块中的catch块和normal块中调用该方法。 –

+0

很好的答案,谢谢 – Ashish

0

你需要一个双if来代替。

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

和OFC让方法2回报的东西(在这种情况下,我让它以方便查看返回布尔)