Ashish
Ashish

Reputation: 1121

Continue Execution even after program catches exception

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?

Thanks for any help.

Upvotes: 2

Views: 12387

Answers (3)

XQEWR
XQEWR

Reputation: 638

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

Upvotes: 1

Juned Ahsan
Juned Ahsan

Reputation: 68715

Simply encapsulate the call of method2 in a try-catch block. Catching the exception will not allow the unhandled exception to be thrown. Do something like this:

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

Upvotes: 4

Voidpaw
Voidpaw

Reputation: 920

You need a double if instead.

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)

Upvotes: 0

Related Questions