AutoTester999
AutoTester999

Reputation: 616

Message of Custom Exception Thrown Being Printed as Null

Even though I have entered a custom message, that is not being printed when I print the message. Code below:

public void run() throws Exception {
    try {
        String poNumber=null;
        if(poNumber.equals(null))
        {
            throw new Exception("Services Purchase Order not created.");
        }
    }
    catch (Exception e) {
        info("Custom Exception Message: "+e.getMessage());
    }
}

OUTPUT:

Custom Exception Message: null

Upvotes: 0

Views: 1629

Answers (3)

Nitek
Nitek

Reputation: 2614

You are catching the wrong exception:

poNumber.equals(null)

Will result in a NullPointerException (because you cannot call equals on null). You have to rewrite it like this:

if(null == poNumber)
{
    throw new Exception("Services Purchase Order not created.");
}

Depending on your logging framwork you can also adjust your info() call to be like this

info("Exception occured", e);

so you will know next time which exception occured.

Upvotes: 1

Alaa Abuzaghleh
Alaa Abuzaghleh

Reputation: 1009

public void run() throws Exception {

    try{

    String poNumber=null;
                if(poNumber==null)
                {
                    throw new Exception("Services Purchase Order not created.");
                }
        }



            catch (Exception e) {


                info("Custom Exception Message: "+e.getMessage());

            }

this will give you the message you want

Upvotes: 1

rgettman
rgettman

Reputation: 178303

You haven't thrown your own Exception; you have caused a NullPointerException with poNumber.equals(null), because poNumber is null.

Your catch block caught the NullPointerException, not your Exception, and its message is null.

If you really want to throw your own Exception, then change the condition to use ==, to avoid the NullPointerException.

if (poNumber == null)

Upvotes: 2

Related Questions