📜  Java异常处理中的嵌套try块

📅  最后修改于: 2022-05-13 01:54:53.131000             🧑  作者: Mango

Java异常处理中的嵌套try块

在Java中,我们可以在 try 块中使用 try 块。每次输入 try 语句时,该异常的上下文都会被压入堆栈。下面给出了一个嵌套尝试的示例。
在本例中,内部 try 块(或 try-block2)用于处理 ArithmeticException,即除以零。之后,外部 try 块(或 try-block)处理 ArrayIndexOutOfBoundsException。

示例 1:

class NestedTry {
  
    // main method
    public static void main(String args[])
    {
        // Main try block
        try {
  
            // initializing array
            int a[] = { 1, 2, 3, 4, 5 };
  
            // trying to print element at index 5
            System.out.println(a[5]);
  
            // try-block2 inside another try block
            try {
  
                // performing division by zero
                int x = a[2] / 0;
            }
            catch (ArithmeticException e2) {
                System.out.println("division by zero is not possible");
            }
        }
        catch (ArrayIndexOutOfBoundsException e1) {
            System.out.println("ArrayIndexOutOfBoundsException");
            System.out.println("Element at such index does not exists");
        }
    }
    // end of main method
}
输出:
ArrayIndexOutOfBoundsException
Element at such index does not exists

每当 try 块没有特定异常的 catch 块时,就会检查父 try 块的 catch 块是否存在该异常,如果找到匹配项,则执行该 catch 块。

如果没有任何 catch 块处理异常,则Java运行时系统将处理该异常,并为该异常显示一条系统生成的消息。

示例 2:

class Nesting {
    // main method
    public static void main(String args[])
    {
        // main try-block
        try {
  
            // try-block2
            try {
  
                // try-block3
                try {
                    int arr[] = { 1, 2, 3, 4 };
                    System.out.println(arr[10]);
                }
  
                // handles ArithmeticException if any
                catch (ArithmeticException e) {
                    System.out.println("Arithmetic exception");
                    System.out.println(" try-block1");
                }
            }
  
            // handles ArithmeticException if any
            catch (ArithmeticException e) {
                System.out.println("Arithmetic exception");
                System.out.println(" try-block2");
            }
        }
  
        // handles ArrayIndexOutOfBoundsException if any
        catch (ArrayIndexOutOfBoundsException e4) {
            System.out.print("ArrayIndexOutOfBoundsException");
            System.out.println(" main try-block");
        }
        catch (Exception e5) {
            System.out.print("Exception");
            System.out.println(" handled in main try-block");
        }
    }
}
输出:
ArrayIndexOutOfBoundsException main try-block