0

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

3 Answers 3

2

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)
Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

1

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.