Rethrow an exception like in C++?

Jonathan M Davis jmdavisProg at gmx.com
Thu Mar 7 22:09:14 PST 2013


On Friday, March 08, 2013 06:46:47 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.

No you don't. It doesn't matter what the type you catch with, since Exceptions 
are classes, they retain their original type when they're caught using a base 
class, and when they're rethrown. And the only reason that you'd lose the 
derived type in C++ doing exactly the same thing that you'd do in D would be 
because you were ignorant enough to catch by value rather than reference 
(which arguably shouldn't even be legal given the various hazards in doing 
so).

C++ has no exception capabilities that D doesn't have. If you truly want to 
catch _everything_ and then rethrow it, then just do

try {...}
catch(Throwable t)
{
    ...
    throw t;
}

But you should never catch Throwable or Error unless you know what you're 
doing. Exceptions that are meant to be caught are derived from Exception. So, 
it would be _far_ better to do

try {...}
catch(Exception e)
{
    ...
    throw e;
}

But if all you're going to do is rethrow it, and you don't care about the 
exception's type, then you should just use a scope statement:

scope(failure) ...

- Jonathan M Davis


More information about the Digitalmars-d-learn mailing list