Which Exception to throw when a method try to use

2019-04-03 21:20发布

This question already has an answer here:

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.

3条回答
地球回转人心会变
2楼-- · 2019-04-03 21:50

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

查看更多
Melony?
3楼-- · 2019-04-03 22:01

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?

查看更多
男人必须洒脱
4楼-- · 2019-04-03 22:04

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

查看更多
登录 后发表回答