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












51
















  • 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





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.






Questions::




  • 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


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











share|improve this question




















  • 1





    Yes, it means locale (language, culture) specific implementations. What's wrong with official documentation?

    – default locale
    Jul 28 '14 at 4:38
















51
















  • 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





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.






Questions::




  • 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


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











share|improve this question




















  • 1





    Yes, it means locale (language, culture) specific implementations. What's wrong with official documentation?

    – default locale
    Jul 28 '14 at 4:38














51












51








51


7







  • 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





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.






Questions::




  • 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


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











share|improve this question

















  • 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





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.






Questions::




  • 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


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








java android






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Jul 28 '14 at 4:55









Xaver Kapeller

39.1k107776




39.1k107776










asked Jul 28 '14 at 4:35









DevrathDevrath

22.7k40132186




22.7k40132186








  • 1





    Yes, it means locale (language, culture) specific implementations. What's wrong with official documentation?

    – default locale
    Jul 28 '14 at 4:38














  • 1





    Yes, it means locale (language, culture) specific implementations. What's wrong with official documentation?

    – default locale
    Jul 28 '14 at 4:38








1




1





Yes, it means locale (language, culture) specific implementations. What's wrong with official documentation?

– default locale
Jul 28 '14 at 4:38





Yes, it means locale (language, culture) specific implementations. What's wrong with official documentation?

– default locale
Jul 28 '14 at 4:38












7 Answers
7






active

oldest

votes


















51














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.






share|improve this answer





















  • 3





    "To my understanding, getMessage() returns the name of the exception." This is just wrong. The name of the Exception is found from e.getClass().getSimpleName(). new NullPointerException().getMessage() returns "null", not "NullPointerException".

    – Philip Whitehouse
    Feb 4 '17 at 0:21













  • The trap here, though, is that the method doesn't actually take the locale, so it isn't always possible to get the locale of the user. In particular, the way the exception in this answer has been implemented will only properly localise the exception for a GUI application. For a server-side application, the default locale of the JVM is not the same as that of the user, so the best policy is never to call ResourceBundle.getBundle(String) and always to provide the user's actual locale. (For instance, with web applications, you typically receive information about the user's locale in a header.)

    – Trejkaz
    Jul 9 '18 at 2:15



















4














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.






share|improve this answer



















  • 11





    The documentation clearly says "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()."

    – fool4jesus
    Aug 31 '15 at 18:14



















2














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





share|improve this answer

































    2














    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





    share|improve this answer

































      0














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





      share|improve this answer































        -1














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






        share|improve this answer

































          -1














          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.






          share|improve this answer

























            Your Answer






            StackExchange.ifUsing("editor", function () {
            StackExchange.using("externalEditor", function () {
            StackExchange.using("snippets", function () {
            StackExchange.snippets.init();
            });
            });
            }, "code-snippets");

            StackExchange.ready(function() {
            var channelOptions = {
            tags: "".split(" "),
            id: "1"
            };
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function() {
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled) {
            StackExchange.using("snippets", function() {
            createEditor();
            });
            }
            else {
            createEditor();
            }
            });

            function createEditor() {
            StackExchange.prepareEditor({
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader: {
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            },
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            });


            }
            });














            draft saved

            draft discarded


















            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f24988491%2fdifference-between-e-getmessage-and-e-getlocalizedmessage%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            7 Answers
            7






            active

            oldest

            votes








            7 Answers
            7






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            51














            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.






            share|improve this answer





















            • 3





              "To my understanding, getMessage() returns the name of the exception." This is just wrong. The name of the Exception is found from e.getClass().getSimpleName(). new NullPointerException().getMessage() returns "null", not "NullPointerException".

              – Philip Whitehouse
              Feb 4 '17 at 0:21













            • The trap here, though, is that the method doesn't actually take the locale, so it isn't always possible to get the locale of the user. In particular, the way the exception in this answer has been implemented will only properly localise the exception for a GUI application. For a server-side application, the default locale of the JVM is not the same as that of the user, so the best policy is never to call ResourceBundle.getBundle(String) and always to provide the user's actual locale. (For instance, with web applications, you typically receive information about the user's locale in a header.)

              – Trejkaz
              Jul 9 '18 at 2:15
















            51














            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.






            share|improve this answer





















            • 3





              "To my understanding, getMessage() returns the name of the exception." This is just wrong. The name of the Exception is found from e.getClass().getSimpleName(). new NullPointerException().getMessage() returns "null", not "NullPointerException".

              – Philip Whitehouse
              Feb 4 '17 at 0:21













            • The trap here, though, is that the method doesn't actually take the locale, so it isn't always possible to get the locale of the user. In particular, the way the exception in this answer has been implemented will only properly localise the exception for a GUI application. For a server-side application, the default locale of the JVM is not the same as that of the user, so the best policy is never to call ResourceBundle.getBundle(String) and always to provide the user's actual locale. (For instance, with web applications, you typically receive information about the user's locale in a header.)

              – Trejkaz
              Jul 9 '18 at 2:15














            51












            51








            51







            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.






            share|improve this answer















            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.







            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Dec 8 '16 at 20:55









            Dan Getz

            6,52962450




            6,52962450










            answered Jul 28 '14 at 6:14









            dgmdgm

            1,39011422




            1,39011422








            • 3





              "To my understanding, getMessage() returns the name of the exception." This is just wrong. The name of the Exception is found from e.getClass().getSimpleName(). new NullPointerException().getMessage() returns "null", not "NullPointerException".

              – Philip Whitehouse
              Feb 4 '17 at 0:21













            • The trap here, though, is that the method doesn't actually take the locale, so it isn't always possible to get the locale of the user. In particular, the way the exception in this answer has been implemented will only properly localise the exception for a GUI application. For a server-side application, the default locale of the JVM is not the same as that of the user, so the best policy is never to call ResourceBundle.getBundle(String) and always to provide the user's actual locale. (For instance, with web applications, you typically receive information about the user's locale in a header.)

              – Trejkaz
              Jul 9 '18 at 2:15














            • 3





              "To my understanding, getMessage() returns the name of the exception." This is just wrong. The name of the Exception is found from e.getClass().getSimpleName(). new NullPointerException().getMessage() returns "null", not "NullPointerException".

              – Philip Whitehouse
              Feb 4 '17 at 0:21













            • The trap here, though, is that the method doesn't actually take the locale, so it isn't always possible to get the locale of the user. In particular, the way the exception in this answer has been implemented will only properly localise the exception for a GUI application. For a server-side application, the default locale of the JVM is not the same as that of the user, so the best policy is never to call ResourceBundle.getBundle(String) and always to provide the user's actual locale. (For instance, with web applications, you typically receive information about the user's locale in a header.)

              – Trejkaz
              Jul 9 '18 at 2:15








            3




            3





            "To my understanding, getMessage() returns the name of the exception." This is just wrong. The name of the Exception is found from e.getClass().getSimpleName(). new NullPointerException().getMessage() returns "null", not "NullPointerException".

            – Philip Whitehouse
            Feb 4 '17 at 0:21







            "To my understanding, getMessage() returns the name of the exception." This is just wrong. The name of the Exception is found from e.getClass().getSimpleName(). new NullPointerException().getMessage() returns "null", not "NullPointerException".

            – Philip Whitehouse
            Feb 4 '17 at 0:21















            The trap here, though, is that the method doesn't actually take the locale, so it isn't always possible to get the locale of the user. In particular, the way the exception in this answer has been implemented will only properly localise the exception for a GUI application. For a server-side application, the default locale of the JVM is not the same as that of the user, so the best policy is never to call ResourceBundle.getBundle(String) and always to provide the user's actual locale. (For instance, with web applications, you typically receive information about the user's locale in a header.)

            – Trejkaz
            Jul 9 '18 at 2:15





            The trap here, though, is that the method doesn't actually take the locale, so it isn't always possible to get the locale of the user. In particular, the way the exception in this answer has been implemented will only properly localise the exception for a GUI application. For a server-side application, the default locale of the JVM is not the same as that of the user, so the best policy is never to call ResourceBundle.getBundle(String) and always to provide the user's actual locale. (For instance, with web applications, you typically receive information about the user's locale in a header.)

            – Trejkaz
            Jul 9 '18 at 2:15













            4














            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.






            share|improve this answer



















            • 11





              The documentation clearly says "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()."

              – fool4jesus
              Aug 31 '15 at 18:14
















            4














            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.






            share|improve this answer



















            • 11





              The documentation clearly says "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()."

              – fool4jesus
              Aug 31 '15 at 18:14














            4












            4








            4







            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.






            share|improve this answer













            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.







            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Jul 28 '14 at 4:56









            Subhrajyoti MajumderSubhrajyoti Majumder

            34k105991




            34k105991








            • 11





              The documentation clearly says "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()."

              – fool4jesus
              Aug 31 '15 at 18:14














            • 11





              The documentation clearly says "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()."

              – fool4jesus
              Aug 31 '15 at 18:14








            11




            11





            The documentation clearly says "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()."

            – fool4jesus
            Aug 31 '15 at 18:14





            The documentation clearly says "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()."

            – fool4jesus
            Aug 31 '15 at 18:14











            2














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





            share|improve this answer






























              2














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





              share|improve this answer




























                2












                2








                2







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





                share|improve this answer















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






                share|improve this answer














                share|improve this answer



                share|improve this answer








                edited Jul 28 '14 at 4:44

























                answered Jul 28 '14 at 4:38









                radairadai

                18.6k75197




                18.6k75197























                    2














                    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





                    share|improve this answer






























                      2














                      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





                      share|improve this answer




























                        2












                        2








                        2







                        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





                        share|improve this answer















                        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






                        share|improve this answer














                        share|improve this answer



                        share|improve this answer








                        edited Jul 28 '14 at 4:50









                        Lavekush Agrawal

                        4,39963774




                        4,39963774










                        answered Jul 28 '14 at 4:46









                        Umer KianiUmer Kiani

                        2,46352548




                        2,46352548























                            0














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





                            share|improve this answer




























                              0














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





                              share|improve this answer


























                                0












                                0








                                0







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





                                share|improve this answer













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






                                share|improve this answer












                                share|improve this answer



                                share|improve this answer










                                answered Mar 3 '17 at 11:53









                                sivisivi

                                6,60623640




                                6,60623640























                                    -1














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






                                    share|improve this answer






























                                      -1














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






                                      share|improve this answer




























                                        -1












                                        -1








                                        -1







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






                                        share|improve this answer















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







                                        share|improve this answer














                                        share|improve this answer



                                        share|improve this answer








                                        edited Jul 28 '14 at 4:42

























                                        answered Jul 28 '14 at 4:38









                                        Deepanshu J bediDeepanshu J bedi

                                        1,4031723




                                        1,4031723























                                            -1














                                            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.






                                            share|improve this answer






























                                              -1














                                              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.






                                              share|improve this answer




























                                                -1












                                                -1








                                                -1







                                                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.






                                                share|improve this answer















                                                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.







                                                share|improve this answer














                                                share|improve this answer



                                                share|improve this answer








                                                edited Jun 14 '18 at 3:36









                                                Paul Rooney

                                                12.7k72844




                                                12.7k72844










                                                answered Jul 28 '14 at 5:06









                                                rahulrahul

                                                1




                                                1






























                                                    draft saved

                                                    draft discarded




















































                                                    Thanks for contributing an answer to Stack Overflow!


                                                    • Please be sure to answer the question. Provide details and share your research!

                                                    But avoid



                                                    • Asking for help, clarification, or responding to other answers.

                                                    • Making statements based on opinion; back them up with references or personal experience.


                                                    To learn more, see our tips on writing great answers.




                                                    draft saved


                                                    draft discarded














                                                    StackExchange.ready(
                                                    function () {
                                                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f24988491%2fdifference-between-e-getmessage-and-e-getlocalizedmessage%23new-answer', 'question_page');
                                                    }
                                                    );

                                                    Post as a guest















                                                    Required, but never shown





















































                                                    Required, but never shown














                                                    Required, but never shown












                                                    Required, but never shown







                                                    Required, but never shown

































                                                    Required, but never shown














                                                    Required, but never shown












                                                    Required, but never shown







                                                    Required, but never shown







                                                    Popular posts from this blog

                                                    MongoDB - Not Authorized To Execute Command

                                                    How to fix TextFormField cause rebuild widget in Flutter

                                                    in spring boot 2.1 many test slices are not allowed anymore due to multiple @BootstrapWith