Since dynamic_cast<T*>
does not throw exceptions, one of the try-catch blocks are completely unnecessary.
However you can easily define your own cast function that does indeed throw exception for pointers. That is what I am doing in my own code (simplified code, and mind you I use garbage collection so I can throw pointers without consequence):
template <class Class, class Object>
inline Class* cast (Object* obj)
{
Class* result = dynamic_cast<Class*>(obj);
if( obj != null and result == null ){
throw new ClassCastException(); // unusual, throw bad_cast if you prefer
}
return result;
}
template <class Class, class Object>
inline const Class* cast (const Object* obj)
{
const Class* result = dynamic_cast<const Class*>(obj);
if( obj != null and result == null ){
throw new ClassCastException(); // unusual, throw bad_cast if you prefer
}
return result;
}
On a side note, I also use it as a syntactic sugar for static_cast, but this is only possible because I do not use it to dynamic_cast references and const references:
template <class Class, class Object>
inline Class cast (const Object& obj)
{
return static_cast<Class>(obj);
}
I'd say you are better off implementing your own casting function that is coherent in terms of exception handling and do precisely what you want and expect. I did and never looked back.