GG wrote:
Quote:
Any thoughts on designing classes wheather to throw the exception and
the consumer has to capture it on try catch or wrap all the methods in a
main method
This is the wrap logic
MainMethod{
bool mainRun = false;
try
{
methods...
mainRun = true;
}
catch(Exception e)
{
this.errMessage=e.Message.ToString();
}
return mainRun;
}
and consumer just checks if true or false and if false display the
exception?
MessageBox.Show
Class obj = new class
if (!obj.MainMethod())
MessageBox.Show (obj.ErrMessage)
The answer to this one is that there are errors and there are errors.
As several in this newsgroup have pointed out, this is the wrong
strategy for fatal errors: the types of errors that indicate that
something has gone seriously wrong with your application or the
environment in which it's running. Examples of this might include "out
of memory," "network is down," "database is inaccessible," "table not
found in database," or any number of other serious problems. In these
cases you should throw exceptions.
However, the other posters are dead wrong if the "error" in question is
a normal, expected part of the way your application runs. The most
common example of this being anything that the user does. If the user
types garbage into the "customer name" field, or orders an item that is
out of stock, or makes an invalid request, then these are (from the
user's point of view) errors, but are (from the application's point of
view) business as usual.
In these sorts of cases, your approach has much merit. I use a similar
approach (I return the error string as a return value; an empty string
means "no error".) In addition, in these cases exceptions are the wrong
thing to use, as the situations aren't really "exceptional". As a rule
of thumb, the user should not be able to provoke exceptions within the
application, except by doing physically nasty things like unplugging
network cables.
However, as is usual in programming, it's never quite that easy. There
are many cases in which you don't know, while writing some utility
class, whether a particular condition will be a true error or something
that the application will consider "business as usual" and want to
handle. Sometimes application-level concerns don't translate neatly
across the layers of software. In these cases, it's usually safest to
make the thing an exception, and then catch in those cases in which it
turns out to be "business as usual." Either that, or do what MS did
with their .Parse() routines: add another routine to test for an error
before calling the real routine. Notice that in .NET 2.0 they added
TryParse() all over the place, specifically to address this issue. In
that sense, .TryParse() is like your "return a result" regimen, while
..Parse() throws an exception, and they're meant to be used together.