Java 即使在程序捕获异常后仍继续执行
以下是一个示例:Java 即使在程序捕获异常后仍继续执行,java,exception-handling,Java,Exception Handling,以下是一个示例: class A{ method1(){ int result = //do something if(result > 1){ method2(); } else{ // do something more } } method2(){ try{ // do something } catch(Exception e){ //thr
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块。我怎样才能做到这一点
感谢您的帮助。只需将
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
}
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
}
}
}
如果,则需要一个双
method1()
{
if(result > 1)
{
if(method2()) { execute code }
else { what you wanted to do in the other code }
}
}
ofc让方法2返回一些东西(在本例中,我让它返回bool以便于检查)我认为您需要的是这样的东西:
if(result > 1){
try {
method2();
} catch(Exception e) { //better add specific exception thrwon from method2
// handling the exception gracefully
}
} else{
// do something more
}
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块感谢您的回复。但它最终如何执行else块中的代码呢。你的逻辑是完美的,我只是很难理解它是如何在其他地方结束的block@Ashish我给出的代码将优雅地处理异常。它不会执行else块中的代码。If和else块是相互排斥的,即一次只能执行一个。如果您有一些代码要在If块中的异常和正常else块执行的情况下执行,则在方法中移动else块的代码。然后从if块和normal else块中的catch块调用该方法。谢谢,但是我无法找出try中要抛出的最具体的异常。如果没有特殊的例外,执行会更高,永远不会调用method3对不起,我不明白你所说的“执行会更高,永远不会调用method3”是什么意思。在上述情况下,如果调用异常并将其移动到Catch块中,将自动调用方法3。您不必有特定的异常,很抱歉,这是我的错误,但是如果出现异常时不想调用Method3(),则需要另一个Catch BlockNo我没有,因为如果在方法2中的try块期间发生意外错误,不管怎样,程序仍将运行method3。。。这可以用在非常具体的示例中,其中method3是一种“碰撞预防”方法,在这种情况下,请确保这一想法可行。然而,如果你能避免它,请这样做。附带说明:如果我的回答解决了你的问题,请接受!