Link to home
Start Free TrialLog in
Avatar of bangviz
bangviz

asked on

Exception with null

Hi,

I have some basic question. Please assist me asap.

I have 2 programs which are found in the same package structure. The first program
with the method getDataTagValue uses the 2nd program UtilException.

But the problem when the First program uses Utilexception it does not display the message as mentioned
"tagName [" + tagName + "] cannot be retrieved"
instead it throws null;


First Program
========
    public static synchronized String getDataTagValue( String  tagName,
                                                       Element dataElement
                                                     )
                                                    throws UtilException {
       
        try{
           
            NodeList list = dataElement.getElementsByTagName(tagName);
            String value = list.item(0).getFirstChild().getNodeValue();
            return value.trim();
           
        }catch(Exception ex){
           
            ex.printStackTrace();
            throw new UtilException("tagName [" + tagName + "] cannot be retrieved");

        }
    }


Second Program
==========
public class UtilException extends Exception{


    private String Message;

    public UtilException(){
        super();
    }
   
    public UtilException(String Message) {
        super(Message);
    }
   
    public void setMessage(String Message){
        this.Message = Message;
    }
   
    public String getMessage(){
        return Message;
    }

}

Can anyone assist what changes needs to be made with my utilexception program,
which can display the exact message rather than showing null.

Thanks
bangviz
SOLUTION
Avatar of Mick Barry
Mick Barry
Flag of Australia image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
The reason you have a null pointer exception is you have an anomaly in your code: you don't actually initialize 'Message', you initialize 'message' as you let the superclass do it. It initializes the latter, leaving the former unitialized
Avatar of bangviz
bangviz

ASKER

Hi,

I made changes as mentioned as below and I tried running a testcase on this and I still get the value as null.


public class UtilException extends Exception{

    public UtilException(){
        super();
    }
   
    public UtilException(String Message) {
        super(Message);
    }

}



public class TestException extends TestCase{
   
    public TestException(String arg0) {
        super(arg0);
    }

    public static Test suite() {

        TestSuite  suite = new TestSuite("TestException");

        suite.addTest( new testHarness( "testException") );

        return suite;
    }
   
    public void testException() throws Exception{
       
        UtilException cue = new UtilException();
       
        String ErrorMessage = "Test this";

        System.out.println("Error:" + cue.getMessage());
             
    }  

}

Any ideas.

Thanks
Bangviz
You don't give the exception a message:

>>UtilException cue = new UtilException();

> The reason you have a null pointer exception is you have an anomaly in your code

No NPE was mentioned (nor would one occur).

The problem with the code is that you overide the getMessage() method from the super class.
The Exception class already has support for an error message, so it is not needed.
try this:

        String ErrorMessage = "Test this";
        UtilException cue = new UtilException(ErrorMessage);
        System.out.println("Error:" + cue.getMessage());
>>No NPE was mentioned (nor would one occur).

I meant null, not an exception

>>
The problem with the code is that you overide the getMessage() method from the super class.
The Exception class already has support for an error message, so it is not needed.
>>

(Already explained)
> I meant null, not an exception

Well it what you said that counts.
Lucky I corrected you :)

> (Already explained)

You talked about initializing Message which had nothing to do with it, and didn't mention anything about the superclass.
In fact Message is no longer needed as I explained.
>>You talked about initializing Message which had nothing to do with it

It has everything to do with, since that's the value that's not being initialized and that's the value getting returned by getMessage
bangviz,

Try the code I posted, and let me know if you have any questions.

Additionally if you'l like a default message to be used when one isn't specified use the following:

public class UtilException extends Exception{
    public UtilException(){
        this("Util error");
    }
   
    public UtilException(String Message) {
        super(Message);
    }
}
Avatar of bangviz

ASKER

Objects,

I tried ur code
try this:

        String ErrorMessage = "Test this";
        UtilException cue = new UtilException(ErrorMessage);
        System.out.println("Error:" + cue.getMessage());

But when i run the output i get is Error:null

I'm still not getting the value "Test this";
did u change your exception class as I posted above?
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Theres nothing wrong with the code currently being used to test it.
And adding a main to a class just for testing it is not good practice.
Your current test driver is a far better approach.
Code that's not wrong usually works doesn't it?
>>And adding a main to a class just for testing it is not good practice.

bangviz, as it happens, it's perfectly OK. Once it's tested you get rid of main
> Code that's not wrong usually works doesn't it?

Please read the earlier comments if you don't understand what the problem is.
Creating an extra redundant test driver will make absolutely no difference.
>>if you don't understand what the problem is.

I understand precisely what the problem is thank you ..;-)
Avatar of bangviz

ASKER

Hi,

I made changes as adviced but my test shows Error:null,does not print the value.


public class UtilException extends Exception{

    public UtilException(){
        super();
    }
   
    public UtilException(String Message) {
        super(Message);
    }

//Added this for testing    
public static void main (String[]args) throws CIUtilException{
       
        throw new CIUtilException("Testing");
    }


}



public class TestException extends TestCase{
   
    public TestException(String arg0) {
        super(arg0);
    }

    public static Test suite() {

        TestSuite  suite = new TestSuite("TestException");

        suite.addTest( new testHarness( "testException") );

        return suite;
    }
   
    public void testException() throws Exception{
       
        String ErrorMessage = "Test this";

        UtilException cue = new UtilException(ErrorMessage);

        System.out.println("Error:" + cue.getMessage());
             
    }  

}
If you run just the code i last posted, you'll get:

Exception in thread "main" UtilException: Testing ...
        at UtilException.main(UtilException.java:12)
>>If you run just the code i last posted

To do that, put it in a new directory and do


set classpath=.
javac UtilException.java
java UtilException
Check that you recompiled UtilException and that there isn't another UtilException class in your classpath.
Avatar of bangviz

ASKER

nope not yet...its value=null
If you follow my last comments, you can't fail to get the same result as i did
> If you follow my last comments, you can't fail to get the same result as i did

Obviously thats not the case :-D
Avatar of bangviz

ASKER

i tried as u posted and its

public class UtilException extends Exception{

    public UtilException(){
        super();
    }
   
    public UtilException(String Message) {
        super(Message);
    }

//For test only
    public static void main (String[]args) throws CIUtilException{
       
        throw new CIUtilException("Testing");
    }


}



public class TestException extends TestCase{
   
    public TestException(String arg0) {
        super(arg0);
    }

    public static Test suite() {

        TestSuite  suite = new TestSuite("TestException");

        suite.addTest( new testHarness( "testException") );

        return suite;
    }
   
    public void testException() throws Exception{
       
        String ErrorMessage = "Test this";

        UtilException cue = new UtilException(ErrorMessage);

        System.out.println("Error:" + cue.getMessage());
             
    }  

}
> nope not yet...its value=null

The problem is not with your code.
It looks like you are running an old version of UtilException, make sure you have recompiled it and are using the latest version.
that code won't actually compile (due to the main() you added), which is probably why you are seeing what you are as I posted above
Remove the main from UtilException and recompile it. Then try running your test driver.
>>Obviously thats not the case :-D

That's because it appears it has *not* been tried:

>>i tried as u posted and its

(there follows not the code i posted)
 
public class UtilException extends Exception{

    public UtilException(){
        this("Util Error");
    }
   
    public UtilException(String Message) {
        super(Message);
    }
}



public class TestException extends TestCase{
   
    public TestException(String arg0) {
        super(arg0);
    }

    public static Test suite() {

        TestSuite  suite = new TestSuite("TestException");

        suite.addTest( new testHarness( "testException") );

        return suite;
    }
   
    public void testException() throws Exception{
       
        String ErrorMessage = "Test this";

        UtilException cue = new UtilException(ErrorMessage);

        System.out.println("Error:" + cue.getMessage());
             
    }  

}
>>
throws CIUtilException{
       
        throw new CIUtilException("Testing");
>>

is of course completely different to what i posted
Avatar of bangviz

ASKER

sorry for the confusion its not ciutilexception.
its utilexception.

1) Anyway i removed main method and compiled utilexception and ran the test its value ie Error:null

2) I added the main and compiled utilexception and ran the test its value ie Error:null

Its still not printing the value which is been passed. Is something wrong with utilexception or my testcase?
theres nothing wrong with your code that i can see.
i suspect thers an old class file in your classpath somewhere.

check your classpath and delete any UtilException.class files you find, then recompile and test.
Avatar of bangviz

ASKER

Hi,

The final code looks like this after recompiling once again,checking my classpaths and running my testcase.
The value is still null, Error:null.

Its pretty strange why I'm unable to get the value's passed.


public class UtilException extends Exception{

    public UtilException(){
        super();
    }
   
    public UtilException(String Message) {
        super(Message);
    }

}


import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;

public class TestException extends TestCase{
   
    public TestException(String arg0) {
        super(arg0);
    }

    public static Test suite() {

        TestSuite  suite = new TestSuite("TestException");

        suite.addTest( new testHarness( "testException") );

        return suite;
    }
   
    public void testException() throws Exception{
       
        String ErrorMessage = "Test this";

        UtilException cue = new UtilException(ErrorMessage);

        System.out.println("Error:" + cue.getMessage());
             
    }  

}


Thanks
Bangviz
make the following change to your exception class and run it, and let me know if the println() message gets displayed:

public class UtilException extends Exception{

    public UtilException(){
        super();
    }
   
    public UtilException(String Message) {
        super(Message);
        System.out.println("UtilException ctor called "+Message);
    }

}
Here is the modification to your original code you ll need to incorporate to get the actual exception.

 public static synchronized String getDataTagValue( String  tagName,
                                                       Element dataElement
                                                     )
                                                    throws UtilException {
       
        try{
           
            NodeList list = dataElement.getElementsByTagName(tagName);
            String value = list.item(0).getFirstChild().getNodeValue();
            return value.trim();
           
        }catch(Exception ex){

        if (ex instanceof NullPointerException) {
            String message = "NullPointerException==>";
            for (int i = 0; i < ex.getStackTrace().length; i++) {
                message += ex.getStackTrace()[i].getClassName() + "." +
                    ex.getStackTrace()[i].getMethodName() + "." +
                    ex.getStackTrace()[i].getLineNumber();
            }
           System.out.println(message);
        }
           else{
            ex.printStackTrace();
           }
            throw new UtilException("tagName [" + tagName + "] cannot be retrieved");

        }
    }


Your first program is coded to deliver a UtilException but in your first prog's method code, you catch an Exception (ex) instead. You know this works, because you ask for the stack trace. Then you go and throw a new UtilException, and as CEHJ says, there's no Message in it - so that's where your Null comes from.
If you follow my last comments to the letter (below), you can't go wrong. Your test harness in its current form is not quite right anyway, as you should throw an Exception to test it realistically - at the moment you're just trying to display one of its properties, so it may just as well be any other class. Get the simplest case working first though, using the following:

====================================================================

Simplify your code to test it:


public class UtilException extends Exception{

          public UtilException(){
                    super();
          }

          public UtilException(String Message) {
                    super(Message);
          }

          public static void main(String[] args) throws UtilException {
               throw new UtilException("Testing ...");
          }

}
====================================================================

>>If you run just the code i last posted

To do that, put it in a new directory and do


set classpath=.
javac UtilException.java
java UtilException

====================================================================
CEHJ - your class thorws an Exception itself at line 12.
Yes - it's meant to (that's the test) ;-)
> Your test harness in its current form is not quite right anyway, as you should throw an Exception to test it realistically

not at all necessary, there absolutely no need

> - at the moment you're just trying to display one of its properties

thats what its testing !

> Yes - it's meant to (that's the test) ;-)

What needs to be tested is returning the message from the exception, not that it can be thrown.
We all know exceptions can be thrown.
>>
What needs to be tested is returning the message from the exception, not that it can be thrown.
We all know exceptions can be thrown.
>>

That's what the code i posted does
No thats what the test case does.
My code does both ;-)
So whats wrong with the existing test code?
>>So whats wrong with the existing test code?

It's adds unnecessary complexity at a stage when the class in question is not running as it should
8-)
Good to hear my suggestion fixed the problem :)