Java Throwable getMessage() 方法



描述

Java Throwable getMessage() 方法返回此可丟擲物件的詳細資訊字串。

宣告

以下是java.lang.Throwable.getMessage() 方法的宣告

public String getMessage()

引數

返回值

此方法返回此 Throwable 例項的詳細資訊字串(可以為 null)。

異常

示例:Throwable 的訊息

以下示例演示了 Java Throwable getMessage() 方法的使用。我們定義了一個 raiseException() 方法,該方法在呼叫時丟擲 Throwable。在主方法中,呼叫 raiseException() 方法,並在 catch 塊中使用 getMessage() 方法列印異常字串表示。

package com.tutorialspoint;

public class ThrowableDemo {

   public static void main(String[] args) {

      try {
         raiseException();
      } catch(Throwable e) {
         // print Message of throwable	  
         System.err.println(e.getMessage());
      }
   }
  
   // throws Throwable  
   public static void raiseException() throws Throwable {
      throw new Throwable("This is the new Exception"); 
   }
} 

輸出

讓我們編譯並執行上述程式,這將產生以下結果:

This is the new Exception

示例:異常的訊息

以下示例演示了 Java Throwable getMessage() 方法的使用。我們定義了一個 raiseException() 方法,該方法在呼叫時丟擲 Exception。在主方法中,呼叫 raiseException() 方法,並在 catch 塊中使用 getMessage() 方法列印異常字串表示。

package com.tutorialspoint;

public class ThrowableDemo {

   public static void main(String[] args) {

      try {
         raiseException();
      } catch(Throwable e) {
         // print Message of throwable
         System.err.println(e.getMessage());
      }
   }

   // throws Exception    
   public static void raiseException() throws Exception {
      throw new Exception("This is the new Exception"); 
   }
} 

輸出

讓我們編譯並執行上述程式,這將產生以下結果:

This is the new Exception

示例:獲取 RuntimeException 的訊息

以下示例演示了 Java Throwable getMessage() 方法的使用。我們定義了一個 raiseException() 方法,該方法在呼叫時丟擲 RuntimeException。在主方法中,呼叫 raiseException() 方法,並在 catch 塊中使用 getMessage() 方法列印異常訊息。

package com.tutorialspoint;

public class ThrowableDemo {

   public static void main(String[] args) {

      try {
         raiseException();
      } catch(Throwable e) {
         // print Message of throwable
         System.err.println(e.getMessage());
      }
   }

   // throws RuntimeException    
   public static void raiseException() throws Exception {
      throw new RuntimeException("This is the new Exception"); 
   }
} 

輸出

讓我們編譯並執行上述程式,這將產生以下結果:

This is the new Exception
java_lang_throwable.htm
廣告