Steve Gates
Steve Gates

Reputation: 129

When to throw an exception and when to handle issue elegantly

Lets say I have this code:

public void MyMethod(string Data, List<string> InputData)
{
  //I would assume throwing an exception for nulls would be correct
  if (String.IsNullOrWhiteSpace(Data) || InputData == null)
    throw new ArgumentNullException("Oops");

  if (InputData.Count == 0) 
    //throw exception or use event to raise a problem
    //throw Exception("Empty List")
    //if (DisplayError != null)
    //  DisplayError("Empty List");
}

Now having a empty list is not an exceptional problem so I should cope with it elegantly. One way is to raise an event to notify the problem. Just makes me wonder why I dont just raise the event if the arguments are null.

What is the best practice in this type of issue?

EventHandler Example:

public class MyOtherClass
{
  public event Action<string,List<string>> ItFired;

  public void DoSomething()
  {
     if(ItFired != null)
       ItFired(myString, myList);
  }
}

public class AnotherClass
{
     public void DoSomething()
     {
           var otherclass = new MyOtherClass();
           var myClass = new MyClass();

           otherClass.ItFired += myClass.MyMethod;
     }

}

Upvotes: 2

Views: 131

Answers (1)

Tigran
Tigran

Reputation: 62266

If an empty list is not exceptional problem do not raise exception in that case. Exceptions are for exceptional cases. In this case you can just return some boolean (say) value, that indicates that function is not executed.

If for the caller of that function that would be an exceptional case, then it (caller) will raise an exception.

Good luck.

Upvotes: 4

Related Questions