A question for C++ gurus about exception handling
-
Why does the application jumps into the
catch (B* ex)
and not thecatch (D* ex)
? The dynamic type ofp
isD
and notB
!#include "stdafx.h"
class B
{};class D : public B
{};int _tmain(int argc, _TCHAR* argv[])
{
try
{
B* p = new D;
throw p;
}
catch (D* ex)
{
delete ex;
printf("catch (D* ex)\n");
}
catch (B* ex)
{
delete ex;
printf("catch (B* ex)\n");
}return 0;
}
Regards, Daniel. -- FIND A JOB YOU LOVE, AND YOU'LL NEVER HAVE TO WORK A DAY OF YOUR LIFE. ;)
-
Why does the application jumps into the
catch (B* ex)
and not thecatch (D* ex)
? The dynamic type ofp
isD
and notB
!#include "stdafx.h"
class B
{};class D : public B
{};int _tmain(int argc, _TCHAR* argv[])
{
try
{
B* p = new D;
throw p;
}
catch (D* ex)
{
delete ex;
printf("catch (D* ex)\n");
}
catch (B* ex)
{
delete ex;
printf("catch (B* ex)\n");
}return 0;
}
Regards, Daniel. -- FIND A JOB YOU LOVE, AND YOU'LL NEVER HAVE TO WORK A DAY OF YOUR LIFE. ;)
Object instance is of D but object type is B.
I'll write a suicide note on a hundred dollar bill - Dire Straits
-
Why does the application jumps into the
catch (B* ex)
and not thecatch (D* ex)
? The dynamic type ofp
isD
and notB
!#include "stdafx.h"
class B
{};class D : public B
{};int _tmain(int argc, _TCHAR* argv[])
{
try
{
B* p = new D;
throw p;
}
catch (D* ex)
{
delete ex;
printf("catch (D* ex)\n");
}
catch (B* ex)
{
delete ex;
printf("catch (B* ex)\n");
}return 0;
}
Regards, Daniel. -- FIND A JOB YOU LOVE, AND YOU'LL NEVER HAVE TO WORK A DAY OF YOUR LIFE. ;)
Because p is not a D*. It is a B*, which happens to be pointing to an instance of D. Nonetheless, the type of the pointer has not changed. In other words, it's catching B* because that's what you're throwing. If you want it to catch D*, then you should throw D*. e.g.: throw static_cast(p); It's worth noting that you cannot use dynamic_cast here, because B is not considered a polymorphic type. i.e. It has no virtual functions.