简体   繁体   English

e.getMessage() 和 e.getLocalizedMessage() 之间的区别

[英]Difference between e.getMessage() and e.getLocalizedMessage()

What is the difference between the getMessage<\/code><\/a> and getLocalizedMessage<\/code><\/a> methods on Java exceptions? Java 异常的getMessage<\/code><\/a>和getLocalizedMessage<\/code><\/a>方法有什么区别?

I am using these both methods to get the message thrown by the catch block while performing error handling.我正在使用这两种方法来获取 catch 块在执行错误处理时抛出的消息。 Both of them get me the message from the error handling, but how exactly do these two differ?他们都从错误处理中得到了我的信息,但是这两者到底有什么不同呢?

I did some searching on the Internet and found this answer on Answers.com<\/a> :我在 Internet 上进行了一些搜索,并在Answers.com<\/a>上找到了这个答案:

Java Exceptions inherit their getMessage and getLocalizedMessage methods from Throwable (see the related link). Java 异常从 Throwable 继承其 getMessage 和 getLocalizedMessage 方法(请参阅相关链接)。 The difference is that subclasses should override getLocalizedMessage to provide a locale-specific message.不同之处在于子类应该覆盖 getLocalizedMessage 以提供特定于语言环境的消息。

For example, imaging that you're adapting code from an American-English speaking company\/group to a British-English group.例如,想象您正在将美式英语公司\/团体的代码改编为英式英语团体。 You may want to create custom Exception classes which override the getLocalizedMessage to correct spelling and grammer to what the users and developers who will be using your code might expect.您可能希望创建自定义 Exception 类来覆盖 getLocalizedMessage 以将拼写和语法更正为将使用您的代码的用户和开发人员可能期望的内容。 This can also be used for actual translations of Exception messages.这也可以用于异常消息的实际翻译。

<\/blockquote>


Questions<\/strong> :问题<\/strong>:

As everybody has mentioned above -- 正如大家上面提到的那样 -

To my understanding, getMessage() returns the name of the exception. 据我所知, getMessage()返回异常的名称。 getLocalizedMessage() returns the name of the exception in the local language of the user (Chinese, Japanese etc.). getLocalizedMessage()以用户的本地语言(中文,日文等)返回异常的名称。 In order to make this work, the class you are calling getLocalizedMessage() on must have overridden the getLocalizedMessage() method. 为了使这项工作,您调用getLocalizedMessage()的类必须重写getLocalizedMessage()方法。 If it hasn't, the method of one of it's super classes is called which by default just returns the result of getMessage. 如果没有,则调用其中一个超类的方法,默认情况下只返回getMessage的结果。

In addition to that, I would like to put some code segment explaining how to use it. 除此之外,我想介绍一些代码段来解释如何使用它。

How to use it 如何使用它

Java does nothing magical, but it does provide a way to make our life easier. Java没有什么神奇之处,但确实提供了一种让我们的生活更轻松的方法。 To use getLocalizedMessage() effectively, we have to override the default behavior. 要有效地使用getLocalizedMessage() ,我们必须覆盖默认行为。

import java.util.ResourceBundle;

public class MyLocalizedThrowable extends Throwable {

    ResourceBundle labels = ResourceBundle.getBundle("loc.exc.test.message");

    private static final long serialVersionUID = 1L;
    public MyLocalizedThrowable(String messageKey) {
        super(messageKey);
    }

    public String getLocalizedMessage() {
        return labels.getString(getMessage());
    }
}

java.util.ResourceBundle is used to do localization. java.util.ResourceBundle用于进行本地化。

In this example, you have to place language-specific property files in the loc/exc/test path. 在此示例中,您必须将特定于语言的属性文件放在loc/exc/test路径中。 For example: 例如:

message_fr.properties (containing some key and value): message_fr.properties(包含一些键和值):

key1=this is key one in France

message.properties (containing some key and value): message.properties(包含一些键和值):

key1=this is key one in English

Now, let us assume that our exception generator class is something like 现在,让我们假设我们的异常生成器类就像

public class ExceptionGenerator {

    public void generateException() throws MyLocalizedThrowable {
        throw new MyLocalizedThrowable("key1");
    }
}

and the main class is: 而主要的课程是:

public static void main(String[] args) {
    //Locale.setDefault(Locale.FRANCE);
    ExceptionGenerator eg = new ExceptionGenerator();

    try {
        eg.generateException();
    } catch (MyLocalizedThrowable e) {
        System.out.println(e.getLocalizedMessage());
    }
}

By default, it will return the "English" key value if you are executing in the "English" environment. 默认情况下,如果您在“英语”环境中执行,它将返回“英语”键值。 If you set the local to France, you will get the output from the message_fr file. 如果将local设置为France,则将从message_fr文件中获取输出。

When to use it 什么时候使用它

If your application needs to support l10n/i18n you need to use it. 如果您的应用需要支持l10n / i18n,则需要使用它。 But most of the application does not need to, as most error messages are not for the end customer, but for the support engineer/development engineer. 但是大多数应用程序都不需要,因为大多数错误消息不是针对最终客户,而是针对支持工程师/开发工程师。

It is really surprising - Check the openJDK 7 code of Throwable.java class. 这真的很令人惊讶 - 检查Throwable.java类的openJDK 7代码。

Implementation of getLocalizedMessage is - getLocalizedMessage实现是 -

390     public String getLocalizedMessage() {
391         return getMessage();
392     }

And implemenation of getMessage is - 并且getMessage实现是 -

376     public String getMessage() {
377         return detailMessage;
378     }

And

130     private String detailMessage;

There is no change in implemenation of both method but documentation. 两种方法的实施都没有变化,但是文件。

no. 没有。 it definitely does not mean language specific implementations. 它绝对不意味着语言特定的实现。 it means implementations that use an internationalization (aka i18n) mechanism. 它意味着使用国际化(aka i18n)机制的实现。 see this page for more details of what resource bundles are and how to use them. 有关哪些资源包以及如何使用它们的详细信息,请参阅此页面

the gist is that you place any text in resource files, of which you have many (one per locale/language/etc) and your code uses a mechanism to look up the text in the correct resource file (the link i provided goes into details). 要点是您将任何文本放在资源文件中,其中有许多文件(每个区域设置/语言/等),并且您的代码使用机制在正确的资源文件中查找文本(我提供的链接详细信息) )。

as to when and where this gets used, its entirely up to you. 至于何时何地使用它,完全取决于你。 normally you'd only be concerned about this when you want to present an exception to a non-technical user, who may not know english that well. 通常,当你想向非技术用户提出例外情况时,你只会担心这一点,而非技术用户可能不太了解英语。 so for example, if you're just writing to log (which commonly only technical users read and so isnt a common i18n target) you'd do: 例如,如果您只是写入日志(通常只有技术用户阅读,因此不是常见的i18n目标),您可以:

try {
   somethingDangerous();
} catch (Exception e) {
   log.error("got this: "+e.getMessage());
}

but if you intend to display the exception message to the screen (as a small dialogue, for example) then you might want to display the message in a local language: 但是如果您打算将异常消息显示在屏幕上(例如,作为一个小对话框),那么您可能希望以本地语言显示消息:

try {
   somethingDangerous();
} catch (Exception e) {
   JOptionPane.showMessageDialog(frame,
    e.getLocalizedMessage(),
    "Error",  <---- also best be taken from i18n
    JOptionPane.ERROR_MESSAGE);
}
public String  getMessage() 

Returns the detail message string of this throwable. 返回此throwable的详细消息字符串。

public String getLocalizedMessage() 

Creates a localized description of this throwable. 创建此throwable的本地化描述。 Subclasses may override this method in order to produce a locale-specific message. 子类可以重写此方法以生成特定于语言环境的消息。 For subclasses that do not override this method, the default implementation returns the same result as getMessage() . 对于不重写此方法的子类,默认实现返回与getMessage()相同的结果。

In your case e is nothing but the object of exception ... 在你的情况下,e只是异常的对象......

getLocalizedMessage() u need to override and give your own message ie the meaning for localized message. getLocalizedMessage()你需要覆盖并给出你自己的消息,即本地化消息的含义。

For example ... if there is a null pointer exception ... 例如......如果有空指针异常......

By printing e it will display null 通过打印e,它将显示为null

e.getMessage() ---> NullPointerException

This is what the Throwable.java class have to say. 这就是Throwable.java类必须要说的。 Maybe it can help someone: 也许它可以帮助某人:

/**
 * Returns the detail message string of this throwable.
 *
 * @return  the detail message string of this {@code Throwable} instance
 *          (which may be {@code null}).
 */
public String getMessage() {
    return detailMessage;
}

/**
 * Creates a localized description of this throwable.
 * Subclasses may override this method in order to produce a
 * locale-specific message.  For subclasses that do not override this
 * method, the default implementation returns the same result as
 * {@code getMessage()}.
 *
 * @return  The localized description of this throwable.
 * @since   JDK1.1
 */
public String getLocalizedMessage() {
    return getMessage();
}

The getLocalizedMessage() method of Throwable class is used to get a locale-specific description of the Throwable object when an Exception Occurred. Throwable类的getLocalizedMessage()方法用于在发生异常时获取Throwable对象的特定语言环境的描述 It helps us to modify the description of the Throwable object according to the local Specific message. 它帮助我们根据本地特定消息修改Throwable对象的描述。 For the subclasses which do not override this method, the default implementation of this method returns the same result as getMessage() . 对于不重写此方法的子类,此方法的默认实现返回与getMessage()相同的结果。

Read more here 在这里阅读更多

To my understanding, getMessage returns the name of the exception. 据我所知,getMessage返回异常的名称。 getLocalizedMessage returns the name of the exception in the local language of the user (Chinese, Japanese etc.). getLocalizedMessage以用户的本地语言(中文,日文等)返回异常的名称。 In order to make this work, the class you are calling getLocalizedMessage on must have overridden the getLocalizedMessage method. 为了使这项工作,您调用getLocalizedMessage的类必须重写getLocalizedMessage方法。 If it hasn't, the method of one of it's super classes is called which by default just returns the result of getMessage. 如果没有,则调用其中一个超类的方法,默认情况下只返回getMessage的结果。

So in most cases, the result will be the same but in some cases it will return the exception name in the language of the region where the program is being run. 因此,在大多数情况下,结果将是相同的,但在某些情况下,它将以运行程序的区域的语言返回异常名称。

Does that mean language specific implementations ? 这是否意味着语言特定的实现? like if i use e.getLocalizedMessage() for example my app in English - error will be thrown in English , if i use my app in Spanish - then error will be thrown in Spanish 就像我使用e.getLocalizedMessage()例如我的应用程序用英语 - 如果我用西班牙语使用我的应用程序错误将被抛出英语 - 然后错误将被抛出西班牙语

public String 
getMessage() 

Returns the detail message string of this throwable.





public String 
getLocalizedMessage() 

Creates a localized description of this throwable. 创建此throwable的本地化描述。 Subclasses may override this method in order to produce a locale-specific message. 子类可以重写此方法以生成特定于语言环境的消息。 For subclasses that do not override this method, the default implementation returns the same result as getMessage(). 对于不重写此方法的子类,默认实现返回与getMessage()相同的结果。

In your case e is nothing but the object of exception ... 在你的情况下,e只是异常的对象......

getLocalizedMessage() u need to override and give your own message i.e 
the meaning for localized message. 

For example ... if there is a null pointer exception ... 例如......如果有空指针异常......

By printing e it will display null 通过打印e,它将显示为null

e.getMessage() ---> NullPointerException 

Read more... 阅读更多...

To my understanding, getMessage returns the name of the exception. 据我所知, getMessage返回异常的名称。

getLocalizedMessage returns the name of the exception in the local language of the user (Chinese, Japanese etc.). getLocalizedMessage以用户的本地语言(中文,日文等)返回异常的名称。

In order to make this work, the class you are calling getLocalizedMessage on must have overridden the getLocalizedMessage method. 为了使这项工作,您调用getLocalizedMessage的类必须重写getLocalizedMessage方法。

If it hasn't, the method of one of it's super classes is called which by default just returns the result of getMessage . 如果没有,则调用其中一个超类的方法,默认情况下只返回getMessage的结果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM