Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
415 views
in Technique[技术] by (71.8m points)

java - Exception.getMessage() is null

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You are catching a different exception to the one that your code is explicitly creating and throwing1. 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 message2.


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 use e.printStackTrace(), a logger call, or a debugger to see which exception you have actually caught.
2 - This is not true on Android. There, an NPE has a helpful message that gives contextual information. It is also no longer true in Java 14 and later; see https://openjdk.java.net/projects/jdk/14/ and https://openjdk.java.net/jeps/358


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...