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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。