Java教程-Java嵌套try块

Java嵌套try块
在Java中,允许在另一个try块内使用try块。这称为嵌套try块。每个我们在try块中输入的语句,其异常上下文都会被推入堆栈。
例如,内部try块可以用于处理ArrayIndexOutOfBoundsException,而外部try块可以处理ArithmeticException(除以零)。
为什么使用嵌套try块
有时候,一个代码块的一部分可能会引发一个错误,而整个代码块本身可能会引发另一个错误。在这种情况下,需要嵌套异常处理程序。
语法:
....
//主尝试块
try
{
statement 1;
statement 2;
//在另一个 try 块中尝试 catch 块
try
{
statement 3;
statement 4;
//嵌套try块中的try catch块
try
{
statement 5;
statement 6;
}
catch(Exception e2)
{
//异常信息
}
}
catch(Exception e1)
{
//异常信息
}
}
//父(外部)try块的catch块
catch(Exception e3)
{
//异常信息
}
....
Java嵌套try示例
示例1
让我们看一个在两个不同异常中嵌套try块的示例
NestedTryBlock.java
public class NestedTryBlock{
public static void main(String args[]){
//外部尝试块
try{
//内部尝试块1
try{
System.out.println("going to divide by 0");
int b =39/0;
}
//内部try块1的catch块
catch(ArithmeticException e)
{
System.out.println(e);
}
//内部尝试块2
try{
int a[]=new int[5];
//赋值超出数组边界
a[5]=4;
}
//内部try块2的catch块
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(e);
}
System.out.println("other statement");
}
//外部try块的catch块
catch(Exception e)
{
System.out.println("handled the exception (outer catch)");
}
System.out.println("normal flow..");
}
}
输出:
图1
当任何try块没有为特定异常提供catch块时,会检查外部(父)try块的catch块,如果匹配,则执行外部try块的catch块。
如果代码中指定的所有catch块都无法处理异常,那么Java运行时系统将处理该异常。然后它会显示该异常的系统生成消息。
示例2
考虑以下示例。在这里,嵌套try块中的try块2不处理异常。然后,控制权转移到其父try块(try块1)。如果它不处理异常,则控制权转移到主try块(外部try块),其中适当的catch块处理异常。这被称为嵌套。
NestedTryBlock.java
public class NestedTryBlock2 {
public static void main(String args[])
{
// 外部(主)try 块
try {
//内部尝试块1
try {
//内部尝试块 2
try {
int arr[] = { 1, 2, 3, 4 };
//打印数组元素超出其边界
System.out.println(arr[10]);
}
// 处理 ArithmeticException
catch (ArithmeticException e) {
System.out.println("Arithmetic exception");
System.out.println(" inner try block 2");
}
}
// 处理 ArithmeticException
catch (ArithmeticException e) {
System.out.println("Arithmetic exception");
System.out.println("inner try block 1");
}
}
// 处理 ArrayIndexOutOfBoundsException
catch (ArrayIndexOutOfBoundsException e4) {
System.out.print(e4);
System.out.println(" outer (main) try block");
}
catch (Exception e5) {
System.out.print("Exception");
System.out.println(" handled in main try-block");
}
}
}
输出:
图2