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

拟墨画扇 提交于 2020-01-12 11:43:07

问题


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.


回答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?




回答2:


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




回答3:


Like the others I will recommend InvalidOperationException (Because John Skeet said it) :)

If you call a function with a null parameter then i will use ArgumentNullException.



来源:https://stackoverflow.com/questions/1903105/which-exception-to-throw-when-a-method-try-to-use-a-field-that-can-be-null

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!