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
广告
© . All rights reserved.