Component exception design question...

  • Thread starter Thread starter David Whitney
  • Start date Start date
D

David Whitney

Hi, all. I'm looking for a "straw poll" of opinions on two ways to
implement part of an exception hierarchy. Forgive the silly example I
offer, but its what came to mind on the fly as I decided how to
illustrate the question.

Let's assume you have an application called "FruitStore," with a
component called "FruitInventory," and it has a method
AddFruit("fruitname"). The relevant rule for this discussion is that
each "fruitname" in the inventory must be unique.

The broader application FruitStore, which maintains a variety of other
information, has a generic exception called DuplicateDataException.
Upon detection of a duplicate fruit in the AddFruit method, the method
has two options:

1. It can throw the generic DuplicateDataException.
2. It can define and throw its own exception, called
DuplicateFruitException.

Consideration: The DuplicateDataException allows for a string message
as a parameter in its constructor that might say "Duplicate fruit
"fruitname" detected."

Which, if either, would the learned ones here advocate?

Please reply to group...email is long dead.

Thanks,
David
 
I think it all depends on whether the user would care about the difference.
The big thing to avoid is forcing people to write:

catch (DuplicateDataException e)
{
if (e.ToString().IndexOf("fruit") != -1)
{
// handle the exception here
}
}

as this is very bad code. In fact, my example has a common error that will
lead to less robust code.

Being able to figure this out is in general a hard problem, so I tend
towards having more exceptions if you are uncertain about what the user
might want.

--
Eric Gunnerson

Visit the C# product team at http://www.csharp.net
Eric's blog is at http://blogs.gotdotnet.com/ericgu/

This posting is provided "AS IS" with no warranties, and confers no rights.
 
Back
Top