Throwable類的getLocalizedMessage()方法用於在發生異常時獲取Throwable對象的locale-specific描述。它有助於我們根據本地特定消息修改Throwable對象的描述。對於不覆蓋此方法的子類,此方法的默認實現返回與getMessage()相同的結果。
用法:
public String getLocalizedMessage()
返回值:發生異常時,此方法返回Throwable對象的locale-specific描述。
下麵的程序演示了Throwable類的getLocalizedMessage()方法:
示例1:
// Java program to demonstrate
// the getLocalizedMessage() Method.
import java.io.*;
class GFG {
// Main Method
public static void main(String[] args)
throws Exception
{
try {
// add the numbers
addPositiveNumbers(2, -1);
}
catch (Exception e) {
System.out.println("LocalizedMessage = "
+ e.getLocalizedMessage());
}
}
// method which adds two positive number
public static void addPositiveNumbers(int a, int b)
throws Exception
{
if (a < 0 || b < 0) {
throw new Exception("Numbers are not Positive");
}
else {
System.out.println(a + b);
}
}
}
輸出:
LocalizedMessage = Numbers are not Positive
示例2:
// Java program to demonstrate
// the ensureCapacity() Method.
import java.io.*;
class GFG {
// Main Method
public static void main(String[] args)
throws Exception
{
try {
testException();
}
catch (Throwable e) {
System.out.println("LocalizedMessage of Exception : "
+ e.getLocalizedMessage());
}
}
// method which throws IndexOutOfBoundsException
public static void testException()
throws IndexOutOfBoundsException
{
throw new IndexOutOfBoundsException(
"Forcefully Generated Exception");
}
}
輸出:
LocalizedMessage of Exception : Forcefully Generated Exception
參考文獻:
https://docs.oracle.com/javase/10/docs/api/java/lang/Throwable.html#getLocalizedMessage()
相關用法
- Java Throwable toString()用法及代碼示例
- Java Throwable addSuppressed()用法及代碼示例
- Java Throwable initCause()用法及代碼示例
- Java Throwable getStackTrace()用法及代碼示例
- Java Throwable getSuppressed()用法及代碼示例
- Java Throwable getCause()用法及代碼示例
- Java Throwable setStackTrace()用法及代碼示例
- Java Throwable getMessage()用法及代碼示例
- Java Throwable printStackTrace()用法及代碼示例
- Java Throwable fillInStackTrace()用法及代碼示例
- Java Java.util.Collections.rotate()用法及代碼示例
- Java Java lang.Long.byteValue()用法及代碼示例
- Java Java lang.Long.numberOfLeadingZeros()用法及代碼示例
- Java Java lang.Long.highestOneBit()用法及代碼示例
注:本文由純淨天空篩選整理自AmanSingh2210大神的英文原創作品 Throwable getLocalizedMessage() method in Java with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。