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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。