Example program One:
Public classcatchwho { Public Static voidMain (string[] args) {Try { Try { Throw Newarrayindexoutofboundsexception (); } Catch(arrayindexoutofboundsexception e) {System.out.println ("ArrayIndexOutOfBoundsException" + "/Inner layer Try-catch"); } Throw NewArithmeticException (); } Catch(ArithmeticException e) {System.out.println ("Happened ArithmeticException"); } Catch(arrayindexoutofboundsexception e) {System.out.println ("ArrayIndexOutOfBoundsException" + "/outer try-catch"); } } }
Results:
Cause analysis: Because there are two throws in the program that throw two different types of errors, the catch that follows immediately catches the corresponding type of error and performs the appropriate processing.
Because
Example Program 2:
Public classCatchWho2 { Public Static voidMain (string[] args) {Try { Try { Throw Newarrayindexoutofboundsexception (); } Catch(ArithmeticException e) {System.out.println ("ArrayIndexOutOfBoundsException" + "/Inner layer Try-catch"); } Throw NewArithmeticException (); } Catch(ArithmeticException e) {System.out.println ("Happened ArithmeticException"); } Catch(arrayindexoutofboundsexception e) {System.out.println ("ArrayIndexOutOfBoundsException" + "/outer try-catch"); } } }
Results:
Conclusion:
There can be more than one catch statement block, and each block of code captures an exception. It is a syntax error to have two different catch blocks after a try block to catch two of the same type of exception.
With a catch statement, you can only capture objects of the exception class and its subclasses. Therefore, a catch statement block that captures the exception object captures all the "catch" exceptions.
placing catch (Exception e) in front of other catch blocks causes these catch blocks to not execute, so Java does not compile the program.
Java multi-layered exception capture