bug icon indicating copy to clipboard operation
bug copied to clipboard

Misleading NPE from inner class with null outer pointer

Open scabug opened this issue 11 years ago • 4 comments

This snippet fails with a NPE as expected:

class A {
  class B // 1
}

val a: A = null
val b = new a.B // 2

The position that the stack trace points to, however, is (1), not (2) as one would expect when dereferencing a def or a val. This is not helped by not giving an error message that would make this situation clearer (e.g. "Cannot instantiate inner class where outer is null").

See https://github.com/slick/slick/issues/722 for a motivating example.

scabug avatar Mar 24 '14 15:03 scabug

Imported From: https://issues.scala-lang.org/browse/SI-8440?orig=1 Reporter: @szeiger Affected Versions: 2.10.3

scabug avatar Mar 24 '14 15:03 scabug

@retronym said: Null checking outer pointers before the call constructor, rather than inside it, would generate more bytecode. The stack trace does in include the real source of the error one frame up.

scabug avatar Mar 24 '14 15:03 scabug

@szeiger said: I think there are 3 options to improve this, none of them without drawbacks: Either do the null check at the call site (more code), or add an error message in the check at the declaration site (more code), or add a subclass of NPE with such an error message (dependency of generated code on standard library).

scabug avatar Mar 24 '14 16:03 scabug

On recent JVM, this progresses to

java.lang.NullPointerException: Cannot throw exception because "null" is null

because of the throw null idiom.

som-snytt avatar Jun 12 '22 10:06 som-snytt