tags:

views:

87

answers:

3

Hi Stackoverflowers,

In designing your class libraries, When you create a method, when do you decide to throw an Exception, or return a boolean.

For example. public class MathHelper

{
    public int Divide(int x, int y)
    {
       if(y == 0)
       {
          throw new DivideByZeroException("Cannot Divide by Zero");
       }
       return x / y;       
    }
}

This is a simple case, but then you start creating more complex methods.

Which do you prefer?

public void Parse(TextReader reader, string delimeter)
{
    if(reader == null)
    {
       throw new ArgumentNullException("The reader cannot be null");
    }
    if(String.IsNullOrEmpty(delimeter))
    {
       throw new ArgumentNullException("The delimeter cannot be null");
    }
}

public bool Parse(TextReader reader, string delimeter)
{
    if(reader == null)
    {
       logger.Error("Parse failed with null reader");
       return false;
    }
    if(String.IsNullOrEmpty(delimeter))
    {
       logger.Error("Parse failed with null delimeter");
       return false;
    }
}
+2  A: 
  • Exceptions are generally the way to go for things where failure is not expected as an option.

  • Boolean return values are the way to go for things where failure might be an expected result sometimes.

Thus, in your examples I'd say go with exceptions.

Amber
+2  A: 

The Java documentation has something to say about the standard way to check preconditions:

http://java.sun.com/j2se/1.4.2/docs/guide/lang/assert.html#preconditions

That is, raise an exception if it's public, and use assert if it's private.

Paul Hankin
I really like this answer, because if you using it just for your internal libraries, throwing a exception is expensive.
Rihan Meij
A: 

I like the way C# does what you're asking about in your example. You can get a method (int.Parse) which returns an integer, or throws on error. You also have a method (int.TryParse) which populates a supplied by-reference argument with the integer value, and returns a boolean status code. This way, if you want to get and exception, you do. If you want to handle an error inline using a conditional, that's an option too.

Coderer