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/lang/Throwable.html#getSuppressed()
相关用法
- Java Throwable initCause()用法及代码示例
- Java Throwable getCause()用法及代码示例
- Java Throwable getStackTrace()用法及代码示例
- Java Throwable setStackTrace()用法及代码示例
- Java Throwable addSuppressed()用法及代码示例
- Java Throwable printStackTrace()用法及代码示例
- Java Throwable getLocalizedMessage()用法及代码示例
- Java Throwable toString()用法及代码示例
- Java Throwable getMessage()用法及代码示例
- Java Throwable fillInStackTrace()用法及代码示例
- Java Java.util.Collections.rotate()用法及代码示例
- Java Java.util.Collections.disjoint()用法及代码示例
- Java Java lang.Long.reverse()用法及代码示例
- Java Java lang.Long.numberOfTrailingZeros()用法及代码示例
注:本文由纯净天空筛选整理自AmanSingh2210大神的英文原创作品 Throwable getSuppressed() method in Java with Examples。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。