Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Throw Exception on use Assert?

I have a system where the employeeId must alway exist unless there is some underlying problem.

The way I see it, is that I have two choices to check this code:

1:

public void GetEmployee(Employee employee)  
{  
   bool exists = EmployeeRepository.VerifyIdExists(Employee.Id);  
   if (!exists)   
   {   
     throw new Exception("Id does not exist");  
   }  
}    

or 2:

public void GetEmployee(Employee employee)  
{  
  EmployeeRepository.AssertIfNotFound(Employee.Id);  
}  

Is option #2 acceptable in the C# language?

I like it because it's tidy in that i don't like looking at "throw new Exception("bla bla bla") type messages outsite the class scope.

like image 548
guazz Avatar asked Apr 27 '10 18:04

guazz


2 Answers

As a rule, you should only throw exceptions in exceptional circumstances. Since this one such circumstance, throwing an exception is the right thing to do.

like image 54
Oded Avatar answered Sep 29 '22 09:09

Oded


It depends what you mean by Assert.

You could use Debug.Assert (or Trace.Assert if you want it to also work in release mode). However this is not that useful because it halts the program and pops up a dialog box until a user presses something. This isn't so good for an unmonitored system. So I'd recommend throwing instead in most cases though as you can decide how you want to react to the error - stop the program, or just log and try to continue.

But if we assume that your Assert method checks its argument and possibly throws an exception, then yes I think that's a good way of doing it.

In fact to pick an example, in Jon Skeet's morelinq both methods are used. For example here:

public static IEnumerable<TSource> AssertCount<TSource>(
    this IEnumerable<TSource> source, 
    int count,
    Func<int, int, Exception> errorSelector)
{
    source.ThrowIfNull("source");
    if (count < 0) throw new ArgumentException(null, "count");
    errorSelector.ThrowIfNull("errorSelector");

    return AssertCountImpl(source, count, errorSelector);
}
like image 35
Mark Byers Avatar answered Sep 29 '22 08:09

Mark Byers