Arci
Arci

Reputation: 6819

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?

Upvotes: 48

Views: 75214

Answers (5)

JB Nizet
JB Nizet

Reputation: 691785

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.

Upvotes: 14

bvanvelsen - ACA Group
bvanvelsen - ACA Group

Reputation: 1751

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

Upvotes: 3

Tobias Breßler
Tobias Breßler

Reputation: 316

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.

Upvotes: 2

kostja
kostja

Reputation: 61558

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

Upvotes: 33

anilsinaci
anilsinaci

Reputation: 386

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.

Upvotes: 2

Related Questions