Home >Java >javaTutorial >Nested try blocks
Nested try blocks:
A try block can be placed inside another try block.
If an exception is not caught in the inner try block, it will be propagated to the outer try block.
Exception propagation:
When an exception occurs in the inner block and is not handled by it, it can be caught by the outer block, allowing the program to continue or terminate in a controlled manner.
Example code with nested try:
The following example shows an inner try block that handles division by zero errors, while the outer try block handles access exceptions outside the array boundaries.
Code example:
// Usa um bloco try aninhado. class NestTrys { public static void main(String args[]) { // O array numer é mais longo que denom. int numer[] = { 4, 8, 16, 32, 64, 128, 256, 512 }; int denom[] = { 2, 0, 4, 4, 0, 8 }; try { // Bloco try externo for (int i = 0; i < numer.length; i++) { try { // Bloco try aninhado // Tenta realizar a divisão System.out.println(numer[i] + " / " + denom[i] + " is " + numer[i] / denom[i]); } catch (ArithmeticException exc) { // Captura exceção de divisão por zero System.out.println("Can't divide by Zero!"); } } } catch (ArrayIndexOutOfBoundsException exc) { // Captura exceção de acesso fora dos limites do array System.out.println("No matching element found."); System.out.println("Fatal error - program terminated."); } } }
Program output:
When division by zero occurs, the exception is caught by the internal try block and the program continues.
When an index error occurs outside the bounds of the array, the outer try block catches the exception and terminates the program.~
Example output:
4 / 2 is 2 Can't divide by Zero! 16 / 4 is 4 32 / 4 is 8 Can't divide by Zero! 128 / 8 is 16 No matching element found. Fatal error – program terminated.
Practical use:
Conclusion:
The above is the detailed content of Nested try blocks. For more information, please follow other related articles on the PHP Chinese website!