[Box Backup-dev] Merges
Martin Ebourne
boxbackup-dev@fluffy.co.uk
Fri, 25 Aug 2006 09:34:32 +0100
On Tue, 2006-08-22 at 20:18 +0100, Ben Summers wrote:
> These repeated exception handlers are getting a bit messy. Perhaps
> there's some way to make things easier? Perhaps an error reporting
> function which takes an std::exception?
Unfortunately I don't think there's a really good solution for this one.
The most common way round this is to use macros, but macros are nasty so
I'd only use them as a last resort. Can work quite well though if you're
prepared to put up with the pain.
An exception handler function as you suggest could be written, but it
can only handle one class of exceptions at a time. ie. You'd need one
for std::exceptions, one for unknown exceptions, more for any other
kinds. Hence you still end up with the same number of catch blocks, they
just become smaller (maybe).
A third route would be to use a method caller which provides the
exception wrapping. This would be a template function to which you
passed a functor or method pointer etc. It would then call the
underlying function wrapped in a try catch and do the error handling.
For the simple case this provides the cleanest code, but of course the
called function doesn't get any access to local variables. You can
arrange to have them passed in (by reference if needed) so this can be
simulated, and of course the method still has access to the object it is
called on. But depending on the code this can break up the flow.
Options 2 & 3 also loose the location held in __FILE__ and __LINE__
which is sometimes useful when reporting where errors are caught,
although again that could be passed in if required. The end result gets
a bit messier though.
I was going to use option (3) for a program I worked on earlier on this
year but ultimately didn't due to the __FILE__ problem. I settled on
copy and paste in the end :-( and this with about 8 catch blocks in each
case, in about 6 different places.
Cheers,
Martin.