Rethrow an exception like in C++?

Jonathan M Davis jmdavisProg at gmx.com
Fri Mar 8 15:21:24 PST 2013


On Friday, March 08, 2013 22:04:03 Rob T wrote:
> So this is more efficient or has some other advantages than using
> typeid?
> 
> if ( cast(myException1)e !is null )
> {
> // do stuff with myException1
> }
> else
> if ( cast(myException2)e !is null )
> {
> // do stuff with myException2
> }
> else
> if ( cast ...

I'd have to benchmark it to be 100% sure, but I'd be very surprised if using 
typeid were faster. It involves getting the typeid (which may mean making a 
function call), and I believe that typeid gives you a struct, which then gets 
compared with opEquals. Contrast this with the cast which should be able to 
just look at the vtbl and then set then do the cast if it can or result in 
null if it can't.

Regardless, as I understand it, casting is the "official" way to check whether a 
object is an instance of a particular type.

Also, you can actually make the ifs even shorter if you want to

if(cast(MyException1)e)
{...}
else if(cast(MyException2)e)
{...}

as using a class reference directly in a condition will check whether it's 
null.

- Jonathan M Davis


More information about the Digitalmars-d-learn mailing list