How does Java enable a program that has handled an exception to execute down from where the exception was thrown?

  • 2021-07-18 07:51:51
  • OfStack

Because the exception handling theory in Java supports the termination model, in which after an exception is thrown, the program cannot return to the place where the exception occurred and continue execution. But if we want Java to act like a recovery model now and expect exceptions to continue after handling, is there any solution?

Thoughts:

Put the try block in the while loop, so that you can continue to enter the try block until you get a satisfactory result.

Let's look at the following program:


package exceptions;
class MyException extends Exception {
}
public class ContinueException {
 private static int count;
 private static final int COUNTNUMBER = 1;
 public static void main(String[] args) {
 while (true) {
  try {
  if (++count == COUNTNUMBER) {
   throw new MyException();
  }
  System.out.println("Continue run after throw MyException");
  } catch (MyException e) {
  // TODO: handle exception
  System.out.println("Caught MyException");
  }finally {
  if(count == COUNTNUMBER + 1) break;
  }
 }
 }
}

The program execution result is:

Caught MyException
Continue run after throw MyException

From the results, we can see that after the exception is handled, the program continues to execute down and prints out the results.

This program gives us the idea that if you put the try block in a loop and establish a conditional statement before the statement that throws an exception, it is possible to skip the place where the exception is thrown and execute downward according to the conditional statement.

Summarize


Related articles: