Exception.getMessage()为空 [英] Exception.getMessage() is null
问题描述
在我的Java代码中,它正在检查!null
条件并抛出一个异常
。
例如
try
{
if(stud .getCall()!= null)
acc.Call = stud.getCall()。toString();
else
抛出新异常(数据为空);
}
catch(异常e)
{
logger.error(Some Error+ e.getMessage());
抛出新异常(请检查Manatadatory Field Missing+ e.getMessage());
}
但在日志中我得到:
有些错误null
为什么 e.getMessage
null
?
除了您的代码显式创建和抛出的异常之外,您将捕获一个异常。您捕捉的异常没有消息。您需要记录整个异常,而不仅仅是异常的消息。 (除此之外,这将告诉您捕获的异常的实际类是什么以及创建/抛出异常的位置。)
根据异常不是有一个消息,我猜想这是一个由 stud
或 acc
为null或由 stud.getCall()
返回 null
...或类似的东西。一个 NullPointerException
(即由JVM生成)具有一个 null
message 1 。 / p>
抛出 java.lang.Exception
是坏习惯
您的问题说明了为什么一般来说,创建/抛出一个错误的想法异常
当您抛出异常
时,当您抓到它时,不可能将其与其他(意外)异常区分开来。这就是发生了什么...你遇到了错误的异常。
你应该选择一个更具体的异常,如果没有适当的例外,实现一个你自己的。
1 - 这在Android上是不正确的。在那里,NPE有一个有用的信息,提供了上下文信息。
Inside my Java code, it is checking for !null
condition and throwing an Exception
.
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());
}
But in the logs I am getting:
Some Error null
Why is the e.getMessage
null
?
You are catching an exception other than the one that your code is explicitly creating and throwing. 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
message1.
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 it from other (unexpected) exceptions when you come to catch it. And that is what has happened ... 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 - This is not true on Android. There, an NPE has a helpful message that gives contextual information.
这篇关于Exception.getMessage()为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!