當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Java Throwable toString()用法及代碼示例


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()



相關用法


注:本文由純淨天空篩選整理自AmanSingh2210大神的英文原創作品 Throwable toString() method in Java with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。