Skip to content
Advertisement

Execute the remaining code after handling exception in java? [closed]

I may be silly. But I got interviewed and I was asked question regarding how you will run the remaining code after you will get the exception.

I gave number of approaches :

  1. We can write the code in finally.
  2. We can write the code in catch block. (They do not want to handle with these 2 approaches.)
  3. We can use throw keyword. But I tried practically, It’s not working.

I tried to explain them with throw statement too.

I have referred so many posts. But My doubt is still not cleared.

As example,

  public static void main(String[] args)
  {
      a(); // getting exception here...
      b(); // This method should executed after handling exception
  } 

It will be helpful if you can suggest any approach on this. So I can understand it.

Advertisement

Answer

If you caught your exception and handled it you can just run your b() method after try-catch block:

try {
  a();
} catch(Exception e) {
  handleMyError(e);
}
b();

This way the a() method executes, if exception is thrown it is caught and handled in the method handleMyError(Exception e) and then the execution continues to b() regardless whether the exception was thrown or not.

Advertisement