Java 链式异常

Java 链式异常

链式异常允许将一个异常与另一个异常联系起来,即一个异常描述另一个异常的原因。例如,考虑这样一种情况:一个方法因为试图除以0而抛出一个ArithmeticException,但导致异常的实际原因是一个I/O错误,导致除数为0。该方法将只向调用者抛出ArithmeticException。所以调用者不会知道异常的实际原因。在这种情况下,可以使用链式异常。

在java中支持链式异常的Throwable类的 构造函数

  1. Throwable(Throwable cause) :- 其中cause是导致当前异常的原因。
  2. Throwable(String msg, Throwable cause) :- 其中msg是异常信息,cause是导致当前异常的异常。

Throwable类支持java中的连锁异常的 方法

  1. getCause() 方法 :- 该方法返回异常的实际原因。
  2. initCause(Throwable cause)方法 :- 该方法为调用的异常设置原因。

使用链式异常的例子。

// Java program to demonstrate working of chained exceptions
public class ExceptionHandling
{
    public static void main(String[] args)
    {
        try
        {
            // Creating an exception
            NumberFormatException ex =
                       new NumberFormatException("Exception");
  
            // Setting a cause of the exception
            ex.initCause(new NullPointerException(
                      "This is actual cause of the exception"));
  
            // Throwing an exception with cause.
            throw ex;
        }
  
        catch(NumberFormatException ex)
        {
            // displaying the exception
            System.out.println(ex);
  
            // Getting the actual cause of the exception
            System.out.println(ex.getCause());
        }
    }
}
Java

输出:

java.lang.NumberFormatException: Exception
java.lang.NullPointerException: This is actual cause of the exception
Java

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程

登录

注册