当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Java Throwable getLocalizedMessage()用法及代码示例


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()



相关用法


注:本文由纯净天空筛选整理自AmanSingh2210大神的英文原创作品 Throwable getLocalizedMessage() method in Java with Examples。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。