Reasons to throw a NullReferenceException explicitly?










7















I'm cleaning up some legacy code and I have found methods which explicitly throw a NullReferenceException (e.g.: when checking if some properties of a class are null, or checking configuration). As this type of exception is thrown by CLR in case of a null reference, this seems like a very poor choice of an exception for an application to throw explicitly.



My question is - are there any reasons for which a NullReferenceException would be a good choice for an exception to throw explicitly from code?










share|improve this question
























  • probably not, we check parameters and sometimes we throw ArgumentNullException but this is good for arguments and parameters, for properties not sure...

    – Davide Piras
    Oct 19 '11 at 13:09















7















I'm cleaning up some legacy code and I have found methods which explicitly throw a NullReferenceException (e.g.: when checking if some properties of a class are null, or checking configuration). As this type of exception is thrown by CLR in case of a null reference, this seems like a very poor choice of an exception for an application to throw explicitly.



My question is - are there any reasons for which a NullReferenceException would be a good choice for an exception to throw explicitly from code?










share|improve this question
























  • probably not, we check parameters and sometimes we throw ArgumentNullException but this is good for arguments and parameters, for properties not sure...

    – Davide Piras
    Oct 19 '11 at 13:09













7












7








7


1






I'm cleaning up some legacy code and I have found methods which explicitly throw a NullReferenceException (e.g.: when checking if some properties of a class are null, or checking configuration). As this type of exception is thrown by CLR in case of a null reference, this seems like a very poor choice of an exception for an application to throw explicitly.



My question is - are there any reasons for which a NullReferenceException would be a good choice for an exception to throw explicitly from code?










share|improve this question
















I'm cleaning up some legacy code and I have found methods which explicitly throw a NullReferenceException (e.g.: when checking if some properties of a class are null, or checking configuration). As this type of exception is thrown by CLR in case of a null reference, this seems like a very poor choice of an exception for an application to throw explicitly.



My question is - are there any reasons for which a NullReferenceException would be a good choice for an exception to throw explicitly from code?







.net nullreferenceexception






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 14 '18 at 15:01









Stephen Kennedy

7,329135068




7,329135068










asked Oct 19 '11 at 13:06









Marcin SeredynskiMarcin Seredynski

5,86721725




5,86721725












  • probably not, we check parameters and sometimes we throw ArgumentNullException but this is good for arguments and parameters, for properties not sure...

    – Davide Piras
    Oct 19 '11 at 13:09

















  • probably not, we check parameters and sometimes we throw ArgumentNullException but this is good for arguments and parameters, for properties not sure...

    – Davide Piras
    Oct 19 '11 at 13:09
















probably not, we check parameters and sometimes we throw ArgumentNullException but this is good for arguments and parameters, for properties not sure...

– Davide Piras
Oct 19 '11 at 13:09





probably not, we check parameters and sometimes we throw ArgumentNullException but this is good for arguments and parameters, for properties not sure...

– Davide Piras
Oct 19 '11 at 13:09












6 Answers
6






active

oldest

votes


















9














The documentation for NullReferenceException implies that you shouldn't throw it from an application:




Note that applications throw the ArgumentNullException exception rather than the NullReferenceException exception discussed here.




And I am sure I've seen guidance elsewhere (can't find any at the moment-> it is here https://docs.microsoft.com/en-us/dotnet/standard/design-guidelines/using-standard-exception-types) that you should avoid throwing exception types that the runtime throws (although I'm about to link to something which shows the runtime throwing an "application" exception)




If you're checking properties within a method, before proceeding, it sounds like you might want to replace them with InvalidOperationException:




InvalidOperationException is used in cases when the failure to invoke a method is caused by reasons other than invalid arguments.




Being in the incorrect state for the method call sounds like it fits this definition.






share|improve this answer
































    5














    No, there is no reason to throw a NullReferenceException.



    You always have some more information about the reason for the error, so you should throw an exception that conveys that information.



    If you for example get a null reference as an argument where it's not allowed, you would throw an ArgumentException or ArgumentNullException instead.






    share|improve this answer






























      2














      MSDN says this:




      Note that applications throw the ArgumentNullException exception
      rather than the NullReferenceException exception discussed here.




      So the answer to your question is probably "no".






      share|improve this answer






























        2














        No, NullReferenceException should only be thrown by the framework itself. ArgumentNullException or InvalidOperationException are valid alternatives.






        share|improve this answer




















        • 1





          Shouldn't use NotSupportedException in this case: "For scenarios where it is sometimes possible for the object to perform the requested operation, and the object state determines whether the operation can be performed, see InvalidOperationException.

          – Damien_The_Unbeliever
          Oct 19 '11 at 13:16











        • updated........

          – devdigital
          Oct 19 '11 at 13:20


















        1














        I'm assuming that if the code didn't check you would get a NullReferenceException(NRE) any way so no. However I see no issue with having a application message that better explains the calling mechanism of the particular function with an inner exception type of NRE or ArgumentExecption as that is underling issue that is causing the problem.






        share|improve this answer






























          0














          I can invision senarios where it would make sense to throw it explicitly. The first one that comes to mind is checking properties before a lot of other processing is done before the exception would be encountered by the CLR.






          share|improve this answer























          • Shouldn't ArgumentNullException should be used for these scenarios?

            – DaveHogan
            Dec 9 '11 at 15:16










          Your Answer






          StackExchange.ifUsing("editor", function ()
          StackExchange.using("externalEditor", function ()
          StackExchange.using("snippets", function ()
          StackExchange.snippets.init();
          );
          );
          , "code-snippets");

          StackExchange.ready(function()
          var channelOptions =
          tags: "".split(" "),
          id: "1"
          ;
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function()
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled)
          StackExchange.using("snippets", function()
          createEditor();
          );

          else
          createEditor();

          );

          function createEditor()
          StackExchange.prepareEditor(
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader:
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          ,
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          );



          );













          draft saved

          draft discarded


















          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f7821755%2freasons-to-throw-a-nullreferenceexception-explicitly%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown

























          6 Answers
          6






          active

          oldest

          votes








          6 Answers
          6






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          9














          The documentation for NullReferenceException implies that you shouldn't throw it from an application:




          Note that applications throw the ArgumentNullException exception rather than the NullReferenceException exception discussed here.




          And I am sure I've seen guidance elsewhere (can't find any at the moment-> it is here https://docs.microsoft.com/en-us/dotnet/standard/design-guidelines/using-standard-exception-types) that you should avoid throwing exception types that the runtime throws (although I'm about to link to something which shows the runtime throwing an "application" exception)




          If you're checking properties within a method, before proceeding, it sounds like you might want to replace them with InvalidOperationException:




          InvalidOperationException is used in cases when the failure to invoke a method is caused by reasons other than invalid arguments.




          Being in the incorrect state for the method call sounds like it fits this definition.






          share|improve this answer





























            9














            The documentation for NullReferenceException implies that you shouldn't throw it from an application:




            Note that applications throw the ArgumentNullException exception rather than the NullReferenceException exception discussed here.




            And I am sure I've seen guidance elsewhere (can't find any at the moment-> it is here https://docs.microsoft.com/en-us/dotnet/standard/design-guidelines/using-standard-exception-types) that you should avoid throwing exception types that the runtime throws (although I'm about to link to something which shows the runtime throwing an "application" exception)




            If you're checking properties within a method, before proceeding, it sounds like you might want to replace them with InvalidOperationException:




            InvalidOperationException is used in cases when the failure to invoke a method is caused by reasons other than invalid arguments.




            Being in the incorrect state for the method call sounds like it fits this definition.






            share|improve this answer



























              9












              9








              9







              The documentation for NullReferenceException implies that you shouldn't throw it from an application:




              Note that applications throw the ArgumentNullException exception rather than the NullReferenceException exception discussed here.




              And I am sure I've seen guidance elsewhere (can't find any at the moment-> it is here https://docs.microsoft.com/en-us/dotnet/standard/design-guidelines/using-standard-exception-types) that you should avoid throwing exception types that the runtime throws (although I'm about to link to something which shows the runtime throwing an "application" exception)




              If you're checking properties within a method, before proceeding, it sounds like you might want to replace them with InvalidOperationException:




              InvalidOperationException is used in cases when the failure to invoke a method is caused by reasons other than invalid arguments.




              Being in the incorrect state for the method call sounds like it fits this definition.






              share|improve this answer















              The documentation for NullReferenceException implies that you shouldn't throw it from an application:




              Note that applications throw the ArgumentNullException exception rather than the NullReferenceException exception discussed here.




              And I am sure I've seen guidance elsewhere (can't find any at the moment-> it is here https://docs.microsoft.com/en-us/dotnet/standard/design-guidelines/using-standard-exception-types) that you should avoid throwing exception types that the runtime throws (although I'm about to link to something which shows the runtime throwing an "application" exception)




              If you're checking properties within a method, before proceeding, it sounds like you might want to replace them with InvalidOperationException:




              InvalidOperationException is used in cases when the failure to invoke a method is caused by reasons other than invalid arguments.




              Being in the incorrect state for the method call sounds like it fits this definition.







              share|improve this answer














              share|improve this answer



              share|improve this answer








              edited Aug 14 '18 at 17:02









              Mohd Amir

              33




              33










              answered Oct 19 '11 at 13:11









              Damien_The_UnbelieverDamien_The_Unbeliever

              195k17251338




              195k17251338























                  5














                  No, there is no reason to throw a NullReferenceException.



                  You always have some more information about the reason for the error, so you should throw an exception that conveys that information.



                  If you for example get a null reference as an argument where it's not allowed, you would throw an ArgumentException or ArgumentNullException instead.






                  share|improve this answer



























                    5














                    No, there is no reason to throw a NullReferenceException.



                    You always have some more information about the reason for the error, so you should throw an exception that conveys that information.



                    If you for example get a null reference as an argument where it's not allowed, you would throw an ArgumentException or ArgumentNullException instead.






                    share|improve this answer

























                      5












                      5








                      5







                      No, there is no reason to throw a NullReferenceException.



                      You always have some more information about the reason for the error, so you should throw an exception that conveys that information.



                      If you for example get a null reference as an argument where it's not allowed, you would throw an ArgumentException or ArgumentNullException instead.






                      share|improve this answer













                      No, there is no reason to throw a NullReferenceException.



                      You always have some more information about the reason for the error, so you should throw an exception that conveys that information.



                      If you for example get a null reference as an argument where it's not allowed, you would throw an ArgumentException or ArgumentNullException instead.







                      share|improve this answer












                      share|improve this answer



                      share|improve this answer










                      answered Oct 19 '11 at 13:11









                      GuffaGuffa

                      558k77565881




                      558k77565881





















                          2














                          MSDN says this:




                          Note that applications throw the ArgumentNullException exception
                          rather than the NullReferenceException exception discussed here.




                          So the answer to your question is probably "no".






                          share|improve this answer



























                            2














                            MSDN says this:




                            Note that applications throw the ArgumentNullException exception
                            rather than the NullReferenceException exception discussed here.




                            So the answer to your question is probably "no".






                            share|improve this answer

























                              2












                              2








                              2







                              MSDN says this:




                              Note that applications throw the ArgumentNullException exception
                              rather than the NullReferenceException exception discussed here.




                              So the answer to your question is probably "no".






                              share|improve this answer













                              MSDN says this:




                              Note that applications throw the ArgumentNullException exception
                              rather than the NullReferenceException exception discussed here.




                              So the answer to your question is probably "no".







                              share|improve this answer












                              share|improve this answer



                              share|improve this answer










                              answered Oct 19 '11 at 13:11









                              M4NM4N

                              74.8k40191246




                              74.8k40191246





















                                  2














                                  No, NullReferenceException should only be thrown by the framework itself. ArgumentNullException or InvalidOperationException are valid alternatives.






                                  share|improve this answer




















                                  • 1





                                    Shouldn't use NotSupportedException in this case: "For scenarios where it is sometimes possible for the object to perform the requested operation, and the object state determines whether the operation can be performed, see InvalidOperationException.

                                    – Damien_The_Unbeliever
                                    Oct 19 '11 at 13:16











                                  • updated........

                                    – devdigital
                                    Oct 19 '11 at 13:20















                                  2














                                  No, NullReferenceException should only be thrown by the framework itself. ArgumentNullException or InvalidOperationException are valid alternatives.






                                  share|improve this answer




















                                  • 1





                                    Shouldn't use NotSupportedException in this case: "For scenarios where it is sometimes possible for the object to perform the requested operation, and the object state determines whether the operation can be performed, see InvalidOperationException.

                                    – Damien_The_Unbeliever
                                    Oct 19 '11 at 13:16











                                  • updated........

                                    – devdigital
                                    Oct 19 '11 at 13:20













                                  2












                                  2








                                  2







                                  No, NullReferenceException should only be thrown by the framework itself. ArgumentNullException or InvalidOperationException are valid alternatives.






                                  share|improve this answer















                                  No, NullReferenceException should only be thrown by the framework itself. ArgumentNullException or InvalidOperationException are valid alternatives.







                                  share|improve this answer














                                  share|improve this answer



                                  share|improve this answer








                                  edited Oct 19 '11 at 13:20

























                                  answered Oct 19 '11 at 13:12









                                  devdigitaldevdigital

                                  30.3k882109




                                  30.3k882109







                                  • 1





                                    Shouldn't use NotSupportedException in this case: "For scenarios where it is sometimes possible for the object to perform the requested operation, and the object state determines whether the operation can be performed, see InvalidOperationException.

                                    – Damien_The_Unbeliever
                                    Oct 19 '11 at 13:16











                                  • updated........

                                    – devdigital
                                    Oct 19 '11 at 13:20












                                  • 1





                                    Shouldn't use NotSupportedException in this case: "For scenarios where it is sometimes possible for the object to perform the requested operation, and the object state determines whether the operation can be performed, see InvalidOperationException.

                                    – Damien_The_Unbeliever
                                    Oct 19 '11 at 13:16











                                  • updated........

                                    – devdigital
                                    Oct 19 '11 at 13:20







                                  1




                                  1





                                  Shouldn't use NotSupportedException in this case: "For scenarios where it is sometimes possible for the object to perform the requested operation, and the object state determines whether the operation can be performed, see InvalidOperationException.

                                  – Damien_The_Unbeliever
                                  Oct 19 '11 at 13:16





                                  Shouldn't use NotSupportedException in this case: "For scenarios where it is sometimes possible for the object to perform the requested operation, and the object state determines whether the operation can be performed, see InvalidOperationException.

                                  – Damien_The_Unbeliever
                                  Oct 19 '11 at 13:16













                                  updated........

                                  – devdigital
                                  Oct 19 '11 at 13:20





                                  updated........

                                  – devdigital
                                  Oct 19 '11 at 13:20











                                  1














                                  I'm assuming that if the code didn't check you would get a NullReferenceException(NRE) any way so no. However I see no issue with having a application message that better explains the calling mechanism of the particular function with an inner exception type of NRE or ArgumentExecption as that is underling issue that is causing the problem.






                                  share|improve this answer



























                                    1














                                    I'm assuming that if the code didn't check you would get a NullReferenceException(NRE) any way so no. However I see no issue with having a application message that better explains the calling mechanism of the particular function with an inner exception type of NRE or ArgumentExecption as that is underling issue that is causing the problem.






                                    share|improve this answer

























                                      1












                                      1








                                      1







                                      I'm assuming that if the code didn't check you would get a NullReferenceException(NRE) any way so no. However I see no issue with having a application message that better explains the calling mechanism of the particular function with an inner exception type of NRE or ArgumentExecption as that is underling issue that is causing the problem.






                                      share|improve this answer













                                      I'm assuming that if the code didn't check you would get a NullReferenceException(NRE) any way so no. However I see no issue with having a application message that better explains the calling mechanism of the particular function with an inner exception type of NRE or ArgumentExecption as that is underling issue that is causing the problem.







                                      share|improve this answer












                                      share|improve this answer



                                      share|improve this answer










                                      answered Oct 19 '11 at 13:11









                                      rerunrerun

                                      21.1k53571




                                      21.1k53571





















                                          0














                                          I can invision senarios where it would make sense to throw it explicitly. The first one that comes to mind is checking properties before a lot of other processing is done before the exception would be encountered by the CLR.






                                          share|improve this answer























                                          • Shouldn't ArgumentNullException should be used for these scenarios?

                                            – DaveHogan
                                            Dec 9 '11 at 15:16















                                          0














                                          I can invision senarios where it would make sense to throw it explicitly. The first one that comes to mind is checking properties before a lot of other processing is done before the exception would be encountered by the CLR.






                                          share|improve this answer























                                          • Shouldn't ArgumentNullException should be used for these scenarios?

                                            – DaveHogan
                                            Dec 9 '11 at 15:16













                                          0












                                          0








                                          0







                                          I can invision senarios where it would make sense to throw it explicitly. The first one that comes to mind is checking properties before a lot of other processing is done before the exception would be encountered by the CLR.






                                          share|improve this answer













                                          I can invision senarios where it would make sense to throw it explicitly. The first one that comes to mind is checking properties before a lot of other processing is done before the exception would be encountered by the CLR.







                                          share|improve this answer












                                          share|improve this answer



                                          share|improve this answer










                                          answered Oct 19 '11 at 13:10









                                          ShaneBlakeShaneBlake

                                          9,51422141




                                          9,51422141












                                          • Shouldn't ArgumentNullException should be used for these scenarios?

                                            – DaveHogan
                                            Dec 9 '11 at 15:16

















                                          • Shouldn't ArgumentNullException should be used for these scenarios?

                                            – DaveHogan
                                            Dec 9 '11 at 15:16
















                                          Shouldn't ArgumentNullException should be used for these scenarios?

                                          – DaveHogan
                                          Dec 9 '11 at 15:16





                                          Shouldn't ArgumentNullException should be used for these scenarios?

                                          – DaveHogan
                                          Dec 9 '11 at 15:16

















                                          draft saved

                                          draft discarded
















































                                          Thanks for contributing an answer to Stack Overflow!


                                          • Please be sure to answer the question. Provide details and share your research!

                                          But avoid


                                          • Asking for help, clarification, or responding to other answers.

                                          • Making statements based on opinion; back them up with references or personal experience.

                                          To learn more, see our tips on writing great answers.




                                          draft saved


                                          draft discarded














                                          StackExchange.ready(
                                          function ()
                                          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f7821755%2freasons-to-throw-a-nullreferenceexception-explicitly%23new-answer', 'question_page');

                                          );

                                          Post as a guest















                                          Required, but never shown





















































                                          Required, but never shown














                                          Required, but never shown












                                          Required, but never shown







                                          Required, but never shown

































                                          Required, but never shown














                                          Required, but never shown












                                          Required, but never shown







                                          Required, but never shown







                                          這個網誌中的熱門文章

                                          Barbados

                                          How to read a connectionString WITH PROVIDER in .NET Core?

                                          Node.js Script on GitHub Pages or Amazon S3