📜  在Java中使用 throw、catch 和 instanceof 处理异常

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

在Java中使用 throw、catch 和 instanceof 处理异常

先决条件: Java中的 Try-Catch 块
在Java中,您的程序可能会遇到异常,语言为此提供了 try-catch 语句来处理它们。但是,包含在“try”块中的一段代码可能容易受到多个异常的影响。例如,看看下面的示例代码:

// A sample Java code with a try catch block
// where the try block has only one catch block
// to handle all possible exceptions
  
// importing class Random to generate a random number as input
import java.util.Random;
class A {
    void func(int n)
    {
        try {
  
            // this will throw ArithmeticException if n is 0
            int x = 10 / n;
            int y[] = new int[n];
  
            // this will throw ArrayIndexOutOfBoundsException
            // if the value of x surpasses
            // the highest index of this array
            y[x] = 10;
        }
        catch (Exception e) {
            System.out.println("Exception occurred");
        }
    }
    public static void main(String a[])
    {
        new A().func(new Random().nextInt(10));
    }
}

出现任一异常时的输出

Exception occurred

从上面的代码可以看出,上面提到的两个异常中的任何一个都有可能发生。为了同时处理它们,catch 语句通过传递对 Exception 类的引用来接受任何可能发生的异常,即所有异常类的父类。但是,这个 catch 语句对所有类型的异常都做同样的事情

为不同的异常指定自定义操作

为了在这种情况下指定自定义操作,程序员通常会放置多个 catch 语句,例如在以下示例中:

// A sample Java code with one try block
// having multiple catch blocks to catch
// different exceptions
  
// importing class Random to generate a random number as input
import java.util.Random;
class A {
    void func(int n)
    {
        try {
  
            // this will throw ArithmeticException if n is 0
            int x = 10 / n;
            int y[] = new int[n];
  
            // this will throw ArrayIndexOutOfBoundsException
            // if the value of x surpasses
            // the highest index of this array
            y[x] = 10;
        }
        catch (ArithmeticException e) {
            System.out.println("Dividing by 0");
        }
        catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("That index doesn't exist");
        }
    }
    public static void main(String a[])
    {
        new A().func(new Random().nextInt(10));
    }
}

输出

a) In case of ArithmeticException: Dividing by 0
b) In case of ArrayIndexOutOfBoundsException: That index doesn't exist

使用 instanceof 为不同的异常指定自定义操作

但是,有一种方法可以只使用一个 catch 块来做同样的事情。为此, Java提供了一个运算符: instanceof
通过使用此运算符,我们可以为发生的不同异常指定自定义操作。以下程序演示了如何:

// Java program to demonstrate the use of
// instanceof to specify different actions for
// different exceptions using only one catch block
  
// importing class Random to generate a random number as input
import java.util.Random;
class A {
    void func(int n)
    {
        try {
  
            // this will throw ArithmeticException if n is 0
            int x = 10 / n;
            int y[] = new int[n];
            y[x] = 10;
  
            // this will throw ArrayIndexOutOfBoundsException
            // if the value of x surpasses
            // the highest index of this array
            System.out.println("No exception arose");
        }
        catch (Exception e) {
            if (e instanceof ArithmeticException)
                System.out.println("Can't divide by 0");
            if (e instanceof ArrayIndexOutOfBoundsException)
                System.out.println("This index doesn't exist in this array");
        }
    }
    public static void main(String a[])
    {
        new A().func(new Random().nextInt(10));
    }
}

输出:

a) In case of ArithmeticException: 
Can't divide by 0
b) In case of ArrayIndexOutOfBoundsException: 
This index doesn't exist in this array
c) In case of no exception: No exception arose

通过在异常处理中使用instanceof运算符,很容易达到上述目的,同时也让你的代码不那么复杂。这里需要注意的一点是,一旦try块遇到异常,控件就会直接跳转到catch块进行处理,从而阻止try块的其余部分执行。因此,即使有可能发生多个异常,try 块也只会抛出一个异常,然后将控制权转移到 catch 块。