记录一个今天遇到的小问题,Exception.getMessage() null,和网上这个例子比较相似
For example
try
{
if (stud.getCall() != null)
acc.Call = stud.getCall().toString();
else
throw new Exception("Data is null");
}
catch (Exception e)
{
logger.error("Some Error" + e.getMessage());
throw new Exception("Please check the Manatadatory Field is Missing" + e.getMessage());
}
最后输出结果为:
Some Error null
Answer : You are catching an exception other than the one that your code is explicitly creating and throwing (1). The exception that you are catching doesn't have a message. You need to log the entire exception, not just the exception's message. (Among other things, that would tell you what the caught exception's actual class is and where the exception was created/thrown.)
Based on the fact that the exception doesn't have a message, I'd guess that it is an NPE caused by stud
or acc
being null, or by stud.getCall()
returning null
... or something like that. A NullPointerException
generated natively (i.e. by the JVM) has a null
message(2).
Throwing java.lang.Exception
is Bad Practice
Your problem illustrates why it is generally speaking a bad idea to create/throw Exception
When you throw Exception
it becomes next to impossible to discriminate between it and other (unexpected) exceptions in a catch
clause. And that is what has happened here: you've caught the wrong exception.
You should pick a more specific exception, and if no appropriate one exists, implement one of your own.
1 - You could also use e.printStackTrace()
, a logger call, or a debugger to find out which exception you have actually caught.
2 - This is not true on Android. There, an NPE has a helpful message that gives contextual information.