A
Adam H. Peterson
Hello,
I sometimes find myself writing code something like this:
try {
Derived &d=dynamic_cast<Derived&>(b);
d.do_something_complicated();
// etc....
} catch (std::bad_cast) {
throw Base_error("An object of incorrect type was given....");
}
The catch block is to do error translation if the user provided an
incorrect type, and I detect this in the dynamic_cast<>.
On the other hand, if a bad_cast exception is thrown in
do_something_complicated(), I don't want my catch block to catch that.
The catch block is only for catching and translating an error if it
occurs at _this_ dynamic_cast. However, I can't simply move
do_something_complicated() out of the try block, as that will be outside
d's scope.
I could probably get around this by turning d into a pointer and having
its declaration be outside the block, but then I end up with pointer
syntax and generally more verbose code. Also, there are cases where I'm
catching an exception from a constructor or something, where it's either
impossible or unadvisable to split the declaration and the
initialization of a variable, so the declaration really has to be inside
the try block.
What is the best way to handle this type of situation, so that I can
catch the exception I'm looking for, but not other exceptions in the
same scope that happen to be of the same type?
I sometimes find myself writing code something like this:
try {
Derived &d=dynamic_cast<Derived&>(b);
d.do_something_complicated();
// etc....
} catch (std::bad_cast) {
throw Base_error("An object of incorrect type was given....");
}
The catch block is to do error translation if the user provided an
incorrect type, and I detect this in the dynamic_cast<>.
On the other hand, if a bad_cast exception is thrown in
do_something_complicated(), I don't want my catch block to catch that.
The catch block is only for catching and translating an error if it
occurs at _this_ dynamic_cast. However, I can't simply move
do_something_complicated() out of the try block, as that will be outside
d's scope.
I could probably get around this by turning d into a pointer and having
its declaration be outside the block, but then I end up with pointer
syntax and generally more verbose code. Also, there are cases where I'm
catching an exception from a constructor or something, where it's either
impossible or unadvisable to split the declaration and the
initialization of a variable, so the declaration really has to be inside
the try block.
What is the best way to handle this type of situation, so that I can
catch the exception I'm looking for, but not other exceptions in the
same scope that happen to be of the same type?