RE: G++ and excemtion

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



I believe this is a C++ issue, not a G++ compiler issue.
>From the C++ standard (ISO 14882 15.1 P3) :

"A throw-expression initializes a temporary object, the type of which is 
determined by removing any top-level cv-qualifiers from the static type 
of the operand of throw and adjusting the type from "array of T" or 
"function returning T" to "pointer to T" or "pointer to function returning 
T", respectively."

Note that the type thrown is the *static* (not dynamic) type of the operand 
to the throw statement.  In your example, this is the static type of excp 
(which is ErrorBase, per the parameter definition) in the throw_exception 
function.

So, this is indeed "normal (standard compliant)" (if not your desired) behavior.

Laurent Marzullo writes :
>
> Hello,
>
> Here a little program.
>
> #include <iostream>
>
> class ErrorBase {}
> class Error : public ErrorBase {}
>
> void
> throw_exception( const ErrorBase& excp )
> {
>     throw excp;
> }
> 
> 
> void
> function( void )
> {
>     Error a;
>     throw_exception( a );
> }
> 
> int
> main( void )
> {
>     try
>     {
>         function();
>     }
>     catch ( const Error& err )
>     {
>         std::cerr << "Error\n";
>     }
>     catch ( const ErrorBase& err )
>     {
>         std::cerr << "ErrorBase\n";
>     }
>     catch ( ... )
>     {
>         std::cerr << "Unknown exception !\n";
>     }
> }
> 
> 
> This program call a function which throw an exception of type 'Error' (which
> inherite from 'ErrorBase').
> 
> But the catch bloc only catch ErrorBase exception and not Error ?
> Is it a normal behavior ?
> I know that there's a copy of the object when a throw occur but is it not a copy
> of the real type of the object that must happen ?
> 
> I want my function throw_exception to throw the real type of the object passed
> as parameter. How may I achieve this ?
> 
> May I dynamic_cast to all possible exception that must be passed to
> throw_exception as:
> 
> if ( dynamic_cast<const Error*>( &excp ) != 0 )
>     throw Error();
> else
>     throw excp;
> 
> 
> Any hint, help ??
> 
 


[Index of Archives]     [Linux C Programming]     [Linux Kernel]     [eCos]     [Fedora Development]     [Fedora Announce]     [Autoconf]     [The DWARVES Debugging Tools]     [Yosemite Campsites]     [Yosemite News]     [Linux GCC]

  Powered by Linux