Alex Gordon
Alex Gordon

Reputation: 60841

Checking for possible exceptions vs. wrapping code in try catch

I'm checking for invalid conditions in my method:

public void DoStuff()
{
    int result;
    if (DeviceSettings == null)
        throw new NullReferenceException("Not initialized");
    if (!Serial.IsNotEmpty())
        throw new Exception("The serial number is empty.");
    if (!int.TryParse(Serial, out result))
        throw new ArgumentOutOfRangeException(Serial);

    //do stuff
}

The code looks awkward to me. Is there a more standard approach to implementing logic that verifies that there are no invalid conditions ?

Upvotes: 1

Views: 64

Answers (1)

jkerak
jkerak

Reputation: 317

I like to restrict throwing exceptions to truly "exceptional" situations. For something like you have above, I would have a "response" type of data structure returned from DoStuff() instead of a void, that could contain a list of validation errors.

class Response()
{
     public List<string> errors {get;set;}
}
public Response DoStuff()
{
    var response = new Response();
    int result;
    if (DeviceSettings == null)
        response.errors.Add("Not Initialized");
    if (!Serial.IsNotEmpty())
        response.errors.Add("The serial number is empty.");
    if (!int.TryParse(Serial, out result))
        response.errors.Add("Argument out of range");
    // check your response errors, return if necessary
    //do stuff
    return response;
}

This way, in the case of data validation errors, you get all possible errors instead of just the first one.

Upvotes: 1

Related Questions