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?
Thanks! So it is possible for the exception message to be null even the exception was thrown by Java/ Android itself (NOT via throw new Exception)?
A NullReferenceException exception is thrown by a method that is passed null . Some methods validate the arguments that are passed to them. If they do and one of the arguments is null , the method throws an System.
NullPointerException is thrown when a reference variable is accessed (or de-referenced) and is not pointing to any object. This error can be resolved by using a try-catch block or an if-else condition to check if a reference variable is null before dereferencing it.
Exception messages depend on the transaction being carried out and are meant to inform you of an important or critical event (for example, start date lies in the past, safety stock has been exceeded). By means of the exception messages, you can easily sort out any materials that you need to reprocess manually.
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);
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With