Java中可抛出的 getLocalizedMessage() 方法及示例
Throwable 类的getLocalizedMessage()方法用于在发生异常时获取 Throwable 对象的特定于语言环境的描述。它帮助我们根据本地的Specific消息修改Throwable对象的描述。对于不覆盖该方法的子类,该方法的默认实现返回与getMessage()相同的结果。
句法:
public String getLocalizedMessage()
返回值:此方法在发生异常时返回 Throwable 对象的特定于语言环境的描述。
下面的程序演示了 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 Java()