Java Throwable toString() 方法



描述

Java Throwable toString() 方法返回此可丟擲物件的簡短描述。結果是以下內容的串聯:

  • 此物件的類名
  • ": "(冒號和空格)
  • 呼叫此物件的 getLocalizedMessage() 方法的結果。

如果 getLocalizedMessage 返回 null,則只返回類名。

宣告

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

public String toString()

引數

返回值

此方法返回此可丟擲物件的字串表示形式。

異常

示例:可丟擲物件的字串表示形式

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

package com.tutorialspoint;

public class ThrowableDemo {

   public static void main(String[] args) {

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

輸出

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

java.lang.Throwable: This is the new Exception

示例:異常的字串表示形式

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

package com.tutorialspoint;

public class ThrowableDemo {

   public static void main(String[] args) {

      try {
         raiseException();
      } catch(Throwable e) {
         // print string representation of throwable
         System.err.println(e.toString());
      }
   }

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

輸出

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

java.lang.Exception: This is the new Exception

示例:RuntimeException 的字串表示形式

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

package com.tutorialspoint;

public class ThrowableDemo {

   public static void main(String[] args) {

      try {
         raiseException();
      } catch(Throwable e) {
         // print string representation of throwable
         System.err.println(e.toString());
      }
   }

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

輸出

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

java.lang.RuntimeException: This is the new Exception
java_lang_throwable.htm
廣告
© . All rights reserved.