scala / bug

Scala 2 bug reports only. Please, no questions — proper bug reports only.
https://scala-lang.org
232 stars 21 forks source link

Misleading NPE from inner class with null outer pointer #8440

Open scabug opened 10 years ago

scabug commented 10 years ago

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 commented 10 years ago

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

scabug commented 10 years ago

@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 commented 10 years ago

@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).

som-snytt commented 2 years ago

On recent JVM, this progresses to

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

because of the throw null idiom.