Rethrow an exception like in C++?

Maxim Fomin maxim at maxim-fomin.ru
Thu Mar 7 22:04:59 PST 2013


On Friday, 8 March 2013 at 05:46:48 UTC, Rob T wrote:
> That's very unfortunate, and should be corrected, because it 
> means that you cannot easily catch multiple derived Exception 
> types and rethrow the same derived type. Instead you have to 
> explicitly catch all derived types and rethrow them 
> individually, but that's simply not practical, so you end up 
> catching only the base exception (Throwable?) and rethrow it, 
> but you lose the derived type in the process.
>
> --rt

Actually no.

class myException1 : Exception { this() { super("1"); } }
class myException2 : Exception { this() { super("2"); } }

void foo(bool val)
{
     if (val)
         throw new myException1;
     else
         throw new myException2;
}
void bar(bool val)
{
     try {
         foo(val);
     }
     catch (Exception e) {
         if (typeid(e) == typeid(myException1))
             throw e; // may be downcasted, if necessary
                      // to work with specific fields
     }
}


void main()
{
     try {
         bar(true);
     }
     catch (myException1 e) {}
     bar(false);
}


More information about the Digitalmars-d-learn mailing list