The Right Approach to Exceptions

Robert Jacques sandford at jhu.edu
Sat Feb 18 21:35:52 PST 2012


On Sat, 18 Feb 2012 20:21:46 -0600, Jonathan M Davis <jmdavisProg at gmx.com> wrote:

> On Saturday, February 18, 2012 19:59:52 Robert Jacques wrote:
>> But you _always_ know what went wrong:
>
> No you don't. Take getopt for instance. If I want to appropriately handle what
> went wrong that caused getopt to throw an exception, I need information on
> what went wrong. I need to know what flag failed and why it failed (e.g.
> unknown or it was given an invalid value). Exception doesn't give you any of
> that. You need a more specific exception type to get that information.

There's a difference between knowing what went wrong and knowing how to fix it. That said, I fully agree with your excellent post. My intent wasn't to propose or support the use of error codes, but to observe that effective use typed exceptions tends to look a lot like error code. For instance, the function calling getop knows how to use getop, what getop's exceptions are and can (hopefully) use the exception's extra information to recover gracefully. But now consider the function that calls the function that calls getop. It probably doesn't even know that getop can be called and that its exceptions can be thrown. Even if it did, it probably doesn't have the access to getop needed utilize that information in the recovery process. Worse, if function A could leverage the type exception, it probably means A and B's implementations are heavily coupled leading to long term maintenance issues.

With the number of times 'bad exception hierarchy' has come up in this discussion and the number of times I've seen MyClassException be a simple wrapper around whatever happens to throw inside MyClass, I guess I'm just ready to explorer solutions out of the box. All my brains have been able to come up with so far is a) beef up exception to aid generic recovery code and b) add a TupleException/VariantException that would allow you to express enforce(isFlagGood[i], i, flags[i], "My flag error message"); or something. i.e. a way to provide extra info when available in the leanest possible manner.


More information about the Digitalmars-d mailing list