📜  Java中的可抛出 getSuppressed() 方法及示例

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

Java中的可抛出 getSuppressed() 方法及示例

Throwable 类getSuppressed()方法用于返回一个数组,该数组包含所有被抑制以传递此异常的异常,通常这种抑制由 try-with-resources 语句完成。为了传递异常如果没有抑制异常或禁用抑制,则返回一个空的抑制异常数组。对返回数组的任何更改都不会影响以后对该方法的调用。

句法:

public final Throwable[] getSuppressed()

参数:此方法不接受任何参数。

返回:此方法返回一个数组,其中包含所有被抑制的异常。

下面的程序说明了Throwable 类的 getSuppressed() 方法

示例 1:

// Java program to demonstrate
// the getSuppressed() Method.
  
import java.io.*;
  
class GFG {
  
    // Main Method
    public static void main(String[] args)
        throws Exception
    {
  
        try {
  
            testException1();
        }
  
        catch (Throwable e) {
  
            // get StackTraceElements
            // using getStackTrace()
            Throwable[] suppExe
                = e.getSuppressed();
  
            // print element of suppExe
            for (int i = 0; i < suppExe.length; i++) {
  
                System.out.println("Suppressed Exceptions:");
                System.out.println(suppExe[i]);
            }
        }
    }
  
    // method which throws Exception
    public static void testException1()
        throws Exception
    {
  
        // creating a suppressed Exception
        Exception
            suppressed
            = new ArrayIndexOutOfBoundsException();
  
        // creating a IOException object
        final IOException ioe = new IOException();
  
        // adding suppressed Exception
        ioe.addSuppressed(suppressed);
  
        // throwing IOException
        throw ioe;
    }
}
输出:
Suppressed Exceptions:
java.lang.ArrayIndexOutOfBoundsException

示例 2:

// Java program to demonstrate
// the getSuppressed() Method.
  
import java.io.*;
  
class GFG {
  
    // Main Method
    public static void main(String[] args)
        throws Exception
    {
        try {
  
            // add the numbers
            addPositiveNumbers(2, -1);
        }
  
        catch (Throwable e) {
  
            // get StackTraceElements
            // using getStackTrace()
            Throwable[] suppExe
                = e.getSuppressed();
  
            // print element of stktrace
            System.out.println("Suppressed Exception Array"
                               + " length = "
                               + suppExe.length);
        }
    }
  
    // method which adds two positive number
    public static void addPositiveNumbers(int a, int b)
        throws Exception
    {
  
        // if Numbers are Positive
        // than add or throw Exception
        if (a < 0 || b < 0) {
  
            throw new Exception("Numbers are not Positive");
        }
  
        else {
  
            System.out.println(a + b);
        }
    }
}
输出:
Suppressed Exception Array length = 0

参考:
https://docs.oracle.com/javase/10/docs/api/java Java()