In Java, we can use a try block within a try block. Each time a try statement is entered, the context of that exception is pushed on to a stack. Given below is an example of a nested try.
In this example, inner try block (or try-block2) is used to handle ArithmeticException, i.e., division by zero. After that, the outer try block (or try-block) handles the ArrayIndexOutOfBoundsException.
ArrayIndexOutOfBoundsException Element at such index does not exists
Whenever a try block does not have a catch block for a particular exception, then the catch blocks of parent try block are inspected for that exception, and if a match is found then that catch block is executed.
If none of the catch blocks handles the exception then the Java run-time system will handle the exception and a system generated message would be shown for the exception.
ArrayIndexOutOfBoundsException main try-block
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.