Which Exception to throw when a method try to use a field that can be null?

14,664

Solution 1

Throw InvalidOperationException:

The exception that is thrown when a method call is invalid for the object's current state.

Note that the null reference isn't being passed into the method - it's already there when the method is called - so it's the object's current state which is invalid, not an argument.

However, it would be better to prevent the object from being created in this way to start with, if at all possible - does it have to be a writable property? Would you ever want an instance which did have a null endpoint URI?

Solution 2

NullReferenceException, InvalidArgumentExecption or ApplicationException would all be fine as long as the exception description clearly states what it is that is null.

Share:
14,664

Related videos on Youtube

Ucodia
Author by

Ucodia

Updated on April 17, 2022

Comments

  • Ucodia
    Ucodia 9 months

    I am actually working on a Framework development, which means require a really strong coding methodology.

    I am facing a problem where I do not know which System.Exception derivated class I need to throw. Basically the case is when I have a class with fields that can be optionnaly initialized by the constructor and that have methods using these fields. Which exception must I throw if the user did not initialized these fields? (which means they are null)

    Here is an example:

    public class MyConnection
    {
        private Uri endpointUri;
    
        public Uri EndpointUri
        {
            get
            {
                return this.endpointUri;
            }
    
            set
            {
                this.endpointUri = value;
            }
        }
    
        public MyConnection()
        {
        }
    
        public MyConnection(Uri endpointUri)
        {
            this.endpointUri = endpointUri;
        }
    
        public FileStream GetFile()
        {
            if (this.endpointUri != null)
            {
                // My doer methods
            }
            else
            {
                throw new TheExceptionINeedToThrow("endpointUri", ...);
            }                
        }
    }
    

    Note that I have been reading the whole "Framework Design Guidelines" chapter concerning exception handling and throwing and that I did not found any solution fitting this exact case. Or maybe I misunderstood something ...

    Thanks for your help.

    EDIT : The fact that I provide an empty constructor seems a bit confusing regarding my problem but it is completely voluntary. In some objects that have to comply with a range of different states that cannot be duplicated in multiple objects it is sometimes useful.

  • SLaks
    SLaks about 13 years
    Notice the explicit default constructor, which (probably) implies that he does.
  • Jon Skeet
    Jon Skeet about 13 years
    @SLaks: I've noticed it, but I'm questioning the wisdom of it.
  • Jon Skeet
    Jon Skeet about 13 years
    None of those seem appropriate to me - the first two for reasons I've given elsewhere; the third is completely nondescript in terms of the type itself, and guidance is generally against using ApplicationException these days.
  • Jeff Sternal
    Jeff Sternal about 13 years
    I'm bowing out in deference to the more complete answer!
  • Jeff Yates
    Jeff Yates about 13 years
    @Jon: I'd say guidance is explicitly against ApplicationException
  • Jon Skeet
    Jon Skeet about 13 years
    @Jeff: Indeed - I wouldn't be surprised to see some recommendations for it though, which is why I was slightly cautious :)
  • Justin
    Justin about 13 years
    Well my point was more that it doesn't really matter what exception is thrown as long as its clearly identifiable what's happened.
  • Justin
    Justin about 13 years
    @Jon - why the guidance against ApplicationException?
  • Jeff Sternal
    Jeff Sternal about 13 years
    @Kragen - if you want to handle the exception in code (as opposed to reading about it in a log entry), the exception you choose to throw does matter.
  • Justin
    Justin about 13 years
    @JeffS I'm struggling to imagine a scenario where waiting for an exception to be thrown would be a good way of handling a member property not being set (also see joelonsoftware.com/items/2003/10/13.html)
  • Jeff Sternal
    Jeff Sternal about 13 years
    @Kragen, you may be right - I can imagine some scenarios, but they're pretty unlikely. Then again, as long as there's a good choice that accurately represents what's happened, why not use that in case one of those exotic circumstances arises?
  • Ucodia
    Ucodia about 13 years
    @Kragen, guidelines explains that SystemException (from which common exceptions derives) indicates an exception thrown from the CLR and that ApplicationException indicates an exception thrown from an non-CLR program.
  • Ucodia
    Ucodia about 13 years
    Thanks, this answer is quite satisfying. In fact I think I missunderstood the "state" term used in the book concerning InvalidOperationException.
  • Ucodia
    Ucodia about 13 years
    @Kragen: concerning NullReferenceException, FxCop CA2201 rule say this: msdn.microsoft.com/en-us/library/ms182338(VS.80).aspx
  • Ucodia
    Ucodia about 13 years
    I edited my question and added some more informations concerning the object state and why I provide an empty ctor in my example. So yes in some case these fields can be null.
  • Jon Skeet
    Jon Skeet about 13 years
    @TheRHCP: Fair enough. I guess we don't know enough about your situation to judge - it's worth trying to avoid ever having invalid object state, but sometimes it's tricky.