Re: Exception handling?
On Jun 23, 5:39 pm, Hector Santos <sant9...@nospam.gmail.com> wrote:
public bool SearchForums(string sPattern)
{
try
{
Regex rgx = new Regex(sPattern, RegexOptions.IgnoreCase);
foreach (var forum in ForumsList)
{
MatchCollection matches = rgx.Matches(forum.Description)=
;
if (matches.Count > 0)
{
/// got something
}
}
return true;
}
catch (Exception ex)
{
MessageBox.Show("Regular Expression Error: " + ex.Message);
}
return false
}
(Please don't think I am picking on you, it's just that this snippet
really makes my hear stand up on my back)
That's a horrible way to handle exceptions.
First off, you can't catch an Exception and say ""Regular Expression
Error: ". That's simply false. If nothing else, you could be out of
memory. On a more general note, in many-a-situation, you simply have
no idea what exactly went wrong, and going specific is an error.
I think I know why you did this, too: it's because people who struggle
with exceptions are in over-reaching fear of losing error context,
error context being e.g.: OK, I have this regexException, but once
caught, question is, where exactly did it happen and for what reason
(e.g. what inputs or program state etc). That loss of context is
luckily easily solved in rich execution environments =E0 la .NET: inner
exceptions. So in your case, __if__ you think that you need more
context, you would do an equivalent of:
class MoreSpecificException
{ MoreSpecificException(params, Exception inner) {...} }
ResultType f(params)
{
try
{
workworkwork;
return someresult;
}
catch(RegexException e)
{
throw new MoreSpecificException(additional "context" info, e);
}
}
(But, as I said to RB, you are, just like him, not allowed to write a
try/catch ;-). When you think you need one, stop and think; question
to ask is "where is this caught if I do nothing?").
Second, this function presumes that there's a good context to go on
the screen with error message. That's a BIG presumption. E.g. what if
this is not called from the main thread? What if I want to call it
elsewhere (re-usability is low).
And third, that function STILL can exit with an exception. E.g. OOM,
or other resource shortage happened in your catch. So you potentially
lie to your caller.
All in all, that's a really poor way to write code with exceptions. In
fact, in exception-enabled environments, attempts to write error-
return code (you did that there) are often horribly misguided. Please,
for the love of God, don't do this. One can kinda-sorta escape in MFC,
but IMNSHO even there it's a bad idea.
Goran.