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()
相關用法
- Java LogRecord getMessage()用法及代碼示例
- Java Throwable getSuppressed()用法及代碼示例
- Java Throwable setStackTrace()用法及代碼示例
- Java Throwable getCause()用法及代碼示例
- Java Throwable toString()用法及代碼示例
- Java Throwable getStackTrace()用法及代碼示例
- Java Throwable initCause()用法及代碼示例
- Java Throwable printStackTrace()用法及代碼示例
- Java Throwable addSuppressed()用法及代碼示例
- Java Throwable getLocalizedMessage()用法及代碼示例
- Java Throwable fillInStackTrace()用法及代碼示例
- Java Java lang.Long.numberOfLeadingZeros()用法及代碼示例
- Java Java lang.Long.numberOfTrailingZeros()用法及代碼示例
- Java Java.util.Collections.rotate()用法及代碼示例
- Java Java lang.Long.lowestOneBit()用法及代碼示例
注:本文由純淨天空篩選整理自AmanSingh2210大神的英文原創作品 Throwable getMessage() method in Java with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。