Java.lang.Throwable類的toString()方法,用於返回此Throwable的String表示形式,該表示形式由該對象的類的名稱,冒號和空格(“:”)組成,並且字符串與調用此對象的getLocalizedMessage()方法,如果getLocalizedMessage返回null,則僅返回類名稱。
用法:
public String toString()
返回值:如果發生異常,則此方法返回此Throwable的String表示形式。
以下示例程序旨在說明Throwable類的toString()方法:
示例1:
// Java program to demonstrate
// the toString() Method.
import java.io.*;
class GFG {
// Main Method
public static void main(String[] args)
throws Exception
{
try {
testException();
}
catch (Throwable e) {
// print using tostring()
System.out.println("Exception: "
+ e.toString());
}
}
// method which throws Exception
public static void testException()
throws Exception
{
throw new Exception("New Exception Thrown");
}
}
輸出:
Exception: java.lang.Exception: New Exception Thrown
示例2:
// Java program to demonstrate
// the toString() Method.
import java.io.*;
class GFG {
// Main Method
public static void main(String[] args)
throws Exception
{
try {
// divide two numbers
int a = 4, b = 0;
int c = a / b;
}
catch (Throwable e) {
// print using tostring()
System.out.println("Exception: "
+ e.toString());
}
}
}
輸出:
Exception: java.lang.ArithmeticException: / by zero
參考文獻:
https://docs.oracle.com/javase/10/docs/api/java/lang/Throwable.html#toString()
相關用法
- Java Throwable setStackTrace()用法及代碼示例
- Java Throwable addSuppressed()用法及代碼示例
- Java Throwable getStackTrace()用法及代碼示例
- Java Throwable printStackTrace()用法及代碼示例
- Java Throwable initCause()用法及代碼示例
- Java Throwable getMessage()用法及代碼示例
- Java Throwable getCause()用法及代碼示例
- Java Throwable getSuppressed()用法及代碼示例
- Java Throwable getLocalizedMessage()用法及代碼示例
- Java AtomicLong toString()用法及代碼示例
- Java String toString()用法及代碼示例
- Java Level toString()用法及代碼示例
- Java DigestOutputStream.toString()用法及代碼示例
- Java LocalTime toString()用法及代碼示例
- Java Instant toString()用法及代碼示例
注:本文由純淨天空篩選整理自AmanSingh2210大神的英文原創作品 Throwable toString() method in Java with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。