Rethrow an exception like in C++?
Rob T
alanb at ucora.com
Fri Mar 8 00:39:12 PST 2013
On Friday, 8 March 2013 at 07:58:42 UTC, Jonathan M Davis wrote:
[...]
> Then you can clearly do something here in C++ that I don't
> understand, because
> I have absolutely no idea how you could do anything the
> exception if you did
> catch(...), because there's no variable to work with.
>
Check this out ...
In C++ you can do this
std::exception Trace()
{
try
{
// key item missing from D
throw; // <= rethrow last exception
}
catch( EType1 &E )
{
// do stuff
return new std::exception( ...
}
catch( EType2 &E )
{
// do different stuff
return new std::exception( ...
}
catch(...)
{
// unkown type, do something else
throw new std::exception( ...
}
}
void Foo()
{
try
{
// For example only, I'd never do this!
throw 10;
}
// I don't want to bother with what was
// caught because I really don't need to know
// so I catch whatever it may be.
catch(...)
{
// I let Trace figure it all out.
throw Trace();
}
return;
}
int main()
{
try
{
Foo();
}
catch( std::exception E )
{
std::cout << E.what();
}
return 0;
}
In D, I have to explicitly catch and paste the exception
reference to the function, and that is extra work that could be
avoided if D could rethrow in a blanket catch block.
Eg,
catch // I don't care what I caught
{
// If Trace could rethrow it could figure out what
// was thrown and how to deal with it.
throw Trace();
}
Instead I have to always do this
catch( Exception E )
{
throw Trace( E );
}
That's OK for 20 try catch but specifying catch(Exception E) over
and over adds up when you have to write a lot more of those. Copy
paste helps, but not always.
--rt
More information about the Digitalmars-d-learn
mailing list