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


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


Throwable類的getMessage()方法用於返回Throwable對象的詳細消息,該消息也可以為null。可以使用此方法將異常的詳細消息作為字符串值獲取。

用法:

public String getMessage()

返回值:此方法返回此Throwable實例的詳細消息。


下麵的程序演示java.lang.Throwable類的getMessage()方法

示例1:

// Java program to demonstrate 
// the getMessage() Method. 
  
import java.io.*; 
  
class GFG { 
  
    // Main Method 
    public static void main(String[] args) 
        throws Exception 
    { 
  
        try { 
  
            // divide the numbers 
            divide(2, 0); 
        } 
  
        catch (ArithmeticException e) { 
  
            System.out.println("Message String = "
                               + e.getMessage()); 
        } 
    } 
  
    // method which divide two numbers 
    public static void divide(int a, int b) 
        throws ArithmeticException 
    { 
  
        int c = a / b; 
  
        System.out.println("Result:" + c); 
    } 
}
輸出:
Message String = / by zero

示例2:

// Java program to demonstrate 
// the getMessage() Method. 
  
import java.io.*; 
  
class GFG { 
  
    // Main Method 
    public static void main(String[] args) 
        throws Exception 
    { 
  
        try { 
  
            test(); 
        } 
  
        catch (Throwable e) { 
  
            System.out.println("Message of Exception : "
                               + e.getMessage()); 
        } 
    } 
  
    // method which throws UnsupportedOperationException 
    public static void test() 
        throws UnsupportedOperationException 
    { 
  
        throw new UnsupportedOperationException(); 
    } 
}
輸出:
Message of Exception : null

參考文獻:
https://docs.oracle.com/javase/10/docs/api/java/lang/Throwable.html#getMessage()



相關用法


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