Rethrow an exception like in C++?

Maxim Fomin maxim at maxim-fomin.ru
Fri Mar 8 13:26:47 PST 2013


On Friday, 8 March 2013 at 21:04:06 UTC, Rob T wrote:
> On Friday, 8 March 2013 at 20:46:42 UTC, Jonathan M Davis wrote:
>> On Friday, March 08, 2013 11:56:12 H. S. Teoh wrote:
>>> On Fri, Mar 08, 2013 at 08:52:21PM +0100, Rob T wrote:
>>> > On Friday, 8 March 2013 at 06:05:02 UTC, Maxim Fomin wrote:
>>> > > catch (Exception e) {
>>> > > 
>>> > > if (typeid(e) == typeid(myException1))
>>> > > 
>>> > > throw e; // may be downcasted, if necessary
>>> > > 
>>> > > // to work with specific fields
>>> > > 
>>> > > }
>>> > 
>>> > Isn't it better to check identity in this way?
>>> > 
>>> > if (typeid(e) is typeid(myException1))
>>> 
>>> [...]
>>> 
>>> Couldn't you just do this?
>>> 
>>> auto myExc = cast(myException1)e;
>>> if (myExc !is null) {
>>> // do stuff with myExc
>>> }
>>> 
>>> ?
>>> 
>>> Or am I missing the point here?
>>
>> That's the way that it's supposed to be done. I don't know why 
>> anyone would
>> mess around with typeid that.
>>
>> - Jonathan M Davis
>
> 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 ...
>
> --rt

Please read comments as well as code - they were important.

typeid(e) == typeid(myException) is useful for simple query 
(identity operator is better) and costs here is call to opEquals 
(with identity operator there is simple comparison)

Casting leads to call to _d_isbaseof2() rt function which is 
slower than the first, but it can be a necessity.


More information about the Digitalmars-d-learn mailing list