Java e.getMessage() 和 e.getLocalizedMessage() 的区别

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24988491/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 16:14:28  来源:igfitidea点击:

Difference between e.getMessage() and e.getLocalizedMessage()

javaandroid

提问by Devrath

  • I am using these both methods to get the message thrown by the catch block while performing error handling
  • Both of them get me the message from the error handling but what exactly does these two differ with
  • I did some searching from internet and came up with this answer from here
  • 我正在使用这两种方法来获取执行错误处理时 catch 块抛出的消息
  • 他们都从错误处理中得到了我的消息,但这两者究竟有何不同
  • 我从互联网上进行了一些搜索,并从这里提出了这个答案


Java Exceptions inherit their getMessage and getLocalizedMessage methods from Throwable (see the related link). The difference is that subclasses should override getLocalizedMessage to provide a locale-specific message. 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. This can also be used for actual translations of Exception messages.

Java 异常从 Throwable 继承了它们的 getMessage 和 getLocalizedMessage 方法(请参阅相关链接)。不同之处在于子类应该覆盖 getLocalizedMessage 以提供特定于区域设置的消息。例如,想象您正在将代码从美国英语公司/集团改编为英国英语集团。您可能想要创建自定义 Exception 类来覆盖 getLocalizedMessage 以将拼写和语法更正为将使用您的代码的用户和开发人员可能期望的内容。这也可以用于异常消息的实际翻译。



Questions::

问题::

  • Does that mean language specificimplementations ? 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

  • Need some clear explanation on where and when i can use these methods to my use

  • 这是否意味着language specific实现?例如,如果我使用e.getLocalizedMessage()我的应用程序English- 错误将被抛出English,如果我使用我的应用程序Spanish- 那么错误将被抛出Spanish

  • 需要明确说明何时何地可以使用这些方法

采纳答案by dgm

As everybody has mentioned above --

正如大家上面提到的——

To my understanding, getMessage()returns the name of the exception. getLocalizedMessage()returns the name of the exception in the local language of the user (Chinese, Japanese etc.). In order to make this work, the class you are calling getLocalizedMessage()on must have overridden the getLocalizedMessage()method. 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()返回异常的名称。getLocalizedMessage()以用户的本地语言(中文、日文等)返回异常的名称。为了完成这项工作,您正在调用的类getLocalizedMessage()必须覆盖了该getLocalizedMessage()方法。如果没有,则调用其中一个超类的方法,默认情况下它只返回 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. To use getLocalizedMessage()effectively, we have to override the default behavior.

Java 没有什么神奇之处,但它确实提供了一种使我们的生活更轻松的方法。为了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.ResourceBundleis used to do localization.

java.util.ResourceBundle用于进行本地化。

In this example, you have to place language-specific property files in the loc/exc/testpath. For example:

在此示例中,您必须在loc/exc/test路径中放置特定于语言的属性文件。例如:

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.

默认情况下,如果您在“英语”环境中执行,它将返回“英语”键值。如果您将本地设置为法国,您将从 message_fr 文件中获得输出。

When to use it

何时使用

If your application needs to support l10n/i18n you need to use it. 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.

如果您的应用程序需要支持 l10n/i18n,则需要使用它。但是大多数应用程序不需要,因为大多数错误消息不是针对最终客户的,而是针对支持工程师/开发工程师的。

回答by radai

no. it definitely does not mean language specific implementations. it means implementations that use an internationalization (aka i18n) mechanism. see this pagefor more details of what resource bundles are and how to use them.

不。它绝对不意味着特定于语言的实现。它意味着使用国际化(又名 i18n)机制的实现。有关资源包是什么以及如何使用它们的更多详细信息,请参阅此页面

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);
}

回答by Deepanshu J bedi

To my understanding, getMessage returns the name of the exception. getLocalizedMessage returns the name of the exception in the local language of the user (Chinese, Japanese etc.). In order to make this work, the class you are calling getLocalizedMessage on must have overridden the getLocalizedMessage method. 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 返回异常的名称。getLocalizedMessage 以用户的本地语言(中文、日语等)返回异常的名称。为了完成这项工作,您在其上调用 getLocalizedMessage 的类必须覆盖了 getLocalizedMessage 方法。如果没有,则调用其中一个超类的方法,默认情况下它只返回 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. 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().

创建此 throwable 的本地化描述。子类可以覆盖此方法以生成特定于语言环境的消息。对于不覆盖此方法的子类,默认实现返回与 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...

阅读更多...

回答by Umer Kiani

public String  getMessage() 

Returns the detail message string of this throwable.

返回此 throwable 的详细消息字符串。

public String getLocalizedMessage() 

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

创建此 throwable 的本地化描述。子类可以覆盖此方法以生成特定于语言环境的消息。对于不覆盖此方法的子类,默认实现返回与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.

getLocalizedMessage()您需要覆盖并提供您自己的消息,即本地化消息的含义。

For example ... if there is a null pointer exception ...

例如...如果有空指针异常...

By printing e it will display null

通过打印 e 它将显示 null

e.getMessage() ---> NullPointerException

回答by Subhrajyoti Majumder

It is really surprising - Check the openJDK 7 code of Throwable.javaclass.

这真的很令人惊讶 - 检查Throwable.java类的 openJDK 7 代码。

Implementation of getLocalizedMessageis -

的实现getLocalizedMessage是 -

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

And implemenation of getMessageis -

和实施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.

两种方法的实现都没有变化,但文档。

回答by rahul

To my understanding, getMessagereturns the name of the exception.

据我了解,getMessage返回异常的名称。

getLocalizedMessagereturns 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 getLocalizedMessageon must have overridden the getLocalizedMessagemethod.

为了完成这项工作,您正在调用的类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.

回答by sivi

This is what the Throwable.java class have to say. Maybe it can help someone:

这就是 Throwable.java 类要说的。也许它可以帮助某人:

/**
 * 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();
}