Christian Kruggel <[EMAIL PROTECTED]> writes:

> Why do some constructors throw NullPointers while others don't? I wrote 
> several constructors that called methods to initalize the object.

I can only speculate, but here are some ways I can force a constructor
to throw NullPointerExceptions.

  class A {
    Set s;
    A() { s.add(new Integer(0)); }
  }

Ok, you don't make that kind of silly mistakes.  But it can occur
in some other disguise, and sometimes out of your control:

  class B {
    Set s;
    B(Set t) { s = t; t.add(new Integer(0)); }
  }

This constructor is at the mercy of the client to provide a valid
parameter.  Client code can err in arbitrary ways.

The following is less obvious:

  class C {
    int n;
    C() {
      try {
        BufferedReader r = new BufferedReader(new FileReader("abc"));
        String s = r.readLine();
        n = s.length();
        r.close();
      }
      catch (IOException e) {
        n = -1;
      }
   }

Suppose file "abc" exists, is readable, but is empty.  Then r.readLine()
will return null (and will not throw an exception).  So s.length() will
bomb.

> Well, one of these constructors now throws a NullPointers from without 
> any linenumber and I do not have any idea why so.

Optimizing compilers often discard information regarding line numbers.
When optimized code or even native code throws an exception, no one
knows which line it is; the best the computer can do is to determine
which method is calling which.

If you don't mind the overhead of learning a diagnostic tool and
writing some assertions in logic terms, try out Extended Static
Checker for Java: http://www.research.compaq.com/SRC/esc/Esc.html


----------------------------------------------------------------------
To UNSUBSCRIBE, email to [EMAIL PROTECTED]
with a subject of "unsubscribe". Trouble? Contact [EMAIL PROTECTED]

Reply via email to