Why can't a null-reference exception name the object that has a null reference?

前端 未结 5 2175
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-17 15:48

It seems to me that a lot of my debugging time is spent chasing down null-reference exceptions in complex statements. For instance:

For Each game As IHomeGam         


        
5条回答
  •  既然无缘
    2020-12-17 16:29

    For languages like Java that are compiled to bytecode that gets interpreted by a VM, suppose you have a class X with a field x, and its value is null for a certain reference. If you write

    x.foo()
    

    the bytecode might look like this:

    push Xref           >> top of stack is ref to instance of X with X.x = null
    getField x          >> pops Xref, pushes 'null' on the stack
    invokeMethod foo    >> pops 'null' -> runtime exception
    

    The point is that the operation that needs a non-null reference on the stack to operate on it, like invokeMethod in the example, cannot and does not know where that null reference came from.

提交回复
热议问题