javaandroidexception

Exception message is null?


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?


Solution

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