Detecting what the target object is when NullReferenceException is thrown

后端 未结 10 809
时光说笑
时光说笑 2020-12-03 01:18

I\'m sure we all have received the wonderfully vague \"Object reference not set to instance of an Object\" exception at some time or another. Identifying the object that is

10条回答
  •  [愿得一人]
    2020-12-03 01:28

    The line # and file are usually all you need to find the culprit. If you are the one throwing the exception, consider using an ArgumentNullException, if appropriate, or checking for nulls and throwing NullReferenceExceptions that have more details about the null field.

    Edit @ your edit :)

    AFAIK, you would have to examine the stack trace string to get that line # and file. Your best bet would be to get the innermost exception, and then look at the first line of its stack trace. If you want to be able to programatically parse that information to find out which field caused the null, and do something with that field's name, I fear you will be out of luck.

    @W. Craig Trader

    Good point. For a null value that is passed into the method, an ArgumentNullException should be thrown. For a member variable that has not yet been initialized, something like an InvalidStateException would probably be good to throw. Unfortunately, I can't find any such exception in MSDN. Roll your own?

提交回复
热议问题