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

对于 Java 异常,getMessagegetLocalizedMessage方法之间有什么区别?

在执行错误处理时,我使用这两种方法来获取 catch 块抛出的消息。它们都从错误处理中得到了消息,但是这两者到底有什么不同呢?

我在互联网上搜索了一下,在 问答网站上找到了这个答案:

Java 异常从 Throwable 继承它们的 getMessage 和 getLocalizedMessage 方法(请参阅相关链接)。区别在于,子类应重写 getLocalizedMessage 以提供特定于语言环境的消息。

例如,想象您正在将来自讲美式英语的公司/团队的代码改编成英式英语的团队。您可能希望创建自定义 Exception 类,这些类覆盖 getLocalizedMessage,以便将拼写和语法更正到将要使用您的代码的用户和开发人员可能期望的程度。这也可以用于异常消息的实际翻译。


问题 :

  • 这是否意味着 特定语言实现?如果我使用 e.getLocalizedMessage()例如我的应用程序在 说英语-错误将抛出在 English,如果我使用我的应用程序在 西班牙语-那么错误将抛出在 西班牙语

  • 需要一些明确的解释,在何时何地我可以使用这些方法来使用/

104877 次浏览

no. it definitely does not mean language specific implementations. it means implementations that use an internationalization (aka i18n) mechanism. 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:

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

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.

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

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

In your case e is nothing but the object of exception ...

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

Read more...

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

In your case e is nothing but the object of exception ...

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

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

Implementation of getLocalizedMessage is -

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

And implemenation of getMessage is -

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

And

130     private String detailMessage;

There is no change in implemenation of both method but documentation.

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.

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.

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.

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.

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

message_fr.properties (containing some key and value):

key1=this is key one in France

message.properties (containing some key and value):

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.

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.

This is what the Throwable.java class have to say. 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();
}