Questions about exception handling..............

R

Robin Tucker

I keep reading about exception handling being preferable to "return codes".
I would like to implement some kind of consistent use of exceptions in my
code, but am finding it hard to come up with some definitive rules.

For example, I Try...Catch....Finally, whenever I am either dealing with an
interop object or something that needs to be "disposed" after use. This I
think is a fairly standard rule. However, I'm not "rethrowing" after
dealing with release of resources, rather - I'm returning an error object
(DataError), that can encapsulate the exception. So, the caller logic for
executing a function looks like this:

theError = DoSomething ();
If Not theError.Result = DataError.Results.OK Then

' We failed.

End If

, where "DoSomething" will return <> OK, if it catches and handles an
exception, usually a meaningful error code (similar to HRESULTS I guess).

The confusion for me arises when I read that you should let the exception
propagate to higher and higher levels, while I am tending to deal with the
exception at the lowest possible level and propagate return codes back up
instead. So the question is, is it better to rethrow, or to return an error
code? If one is preferable to the other, why? And won't constantly
rethrowing back up a hierarchy give me performance problems?
 
H

Herfried K. Wagner [MVP]

Robin,

Robin Tucker said:
The confusion for me arises when I read that you should let the exception
propagate to higher and higher levels, while I am tending to deal with the
exception at the lowest possible level and propagate return codes back up
instead. So the question is, is it better to rethrow, or to return an
error code? If one is preferable to the other, why? And won't constantly
rethrowing back up a hierarchy give me performance problems?

I think it's better to propagate the exception. This will prevent the user
(client) of the class from missing to check return values. However,
exceptions are not always the best solution and there are people who are not
as euphoric about today's use of structured exception handling.

Exceptions
<URL:http://www.joelonsoftware.com/items/2003/10/13.html>

Note that you can add information to an exception by creating a new
exception object and adding the existing exception as inner exception. Then
you simply need to throw the new exception.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top