Exception message is null?

60,190

Solution 1

The message and the stacktrace are two distinct pieces of information. While the stackstrace is mandatory, the message is not. Most exceptions carry a message, and it is the best practice to do so, but some just don't and there's nothing to be done to fix it.

You can make it easier for your clients though and provide a message by wrapping the message-less exception or throwing a custom exception with the original exception as the cause. This might look like following.

throw new  MyRuntimeException("Socket was closed unexpectedly", e);

Solution 2

SocketTimeOutException is the type of the exception. It's probably just that this exception (or the code throwing it) didn't bother providing a message with the exception, and thought the type of the exception was sufficiently meaningful. Use

Log.d("Error", "Error Message: " + e);

or

Log.d("Error", "Some exception occurred", e);

rather than asking the message.

Solution 3

e.printstacktrace() means the actual stacktrace which is almost always present. A message however not. If you check the Javadoc of the getMessage() method, you will notice that it may return null. There will be message if you call the constructor from exception with the String message param Exception Javadoc

Solution 4

I think the Exception that is thrown in your code has no message. The String is null. But of course you can print the stack trace. These are two different things. You will see the stack trace, but without the message.

Solution 5

Try to give the exception itself to the logger instead of e.getMessage(). Loggers generally have methods which expect Throwable objects and default configurations (generally) of the loggers prints the stack trace.

Share:
60,190
Arci
Author by

Arci

An Android and J2EE developer.

Updated on June 30, 2020

Comments

  • Arci
    Arci almost 4 years

    I have a try-catch statement in my code. In my catch block, I am calling e.getMessage() to print the message of the exception. However, e.getMessage keeps returning a null value. Interestingly, when I call e.printStackTrace, I have no problem printing the stack trace.

    Below is my code:

    try
    {
        console = new BufferedReader(new InputStreamReader(httpsURLConnection.getInputStream()));
    }catch(Exception e)
    {
        Log.d("Error", "Error Message: " + e.getMessage()); //e.getMessage is returning a null value
        e.printStackTrace(); //this works. is displaying a SocketTimeOutException
    }
    

    What could be the cause of my problem? How do I solve it?