re-throwing an exception

A

ajfish

Hi,

I would like to re-throw an exception but keep the stack trace from
when the exception was originally generated. Is there any way of doing
this (using .Net 1.1)?

I am not throwing it from the same place it was caught (in fact it is
caught in a worker thread which squirrels it away and then the main
thread digs it out later and throws it)

I realise that I could wrap the exeption, but then any calling function
wishing to catch it would have to take special action (to catch the
wrapper rather than the original)

Andy
 
J

Jon Skeet [C# MVP]

I would like to re-throw an exception but keep the stack trace from
when the exception was originally generated. Is there any way of doing
this (using .Net 1.1)?

Yup - just us "throw;". If you do "throw e;" you get a new stack trace,
but you don't with plain "throw;".

Jon
 
J

Josh Twist

Though you can only use 'throw' alone inside the catch block where the
exception was caught.

I'm not sure whether this will be possible with you 'squirrelling it
away'!?

Do you know the exact type of the exception in question? You could
potentially pass the caught exception to a new instance of itself as
the inner exception?

throw new WellKnownException(caughtException.Message, caughtException);

I'm not sure how crazy that idea is?! Obviously, if you're inside the
original catch block, just use throw as Jon suggests.

Josh
http://www.thejoyofcode.com/
 
J

Jon Skeet [C# MVP]

Josh Twist said:
Though you can only use 'throw' alone inside the catch block where the
exception was caught.

I'm not sure whether this will be possible with you 'squirrelling it
away'!?

Whoops - yes, I missed that part. As far as I know there's no way of
avoiding messing with the stack at that point.
 
A

Andy Fish

Josh Twist said:
Though you can only use 'throw' alone inside the catch block where the
exception was caught.

I'm not sure whether this will be possible with you 'squirrelling it
away'!?

Do you know the exact type of the exception in question? You could
potentially pass the caught exception to a new instance of itself as
the inner exception?

throw new WellKnownException(caughtException.Message, caughtException);

I'm not sure how crazy that idea is?! Obviously, if you're inside the
original catch block, just use throw as Jon suggests.

the situation I wanted to achieve was that the caller would always "see" the
original exception that caused the error - regardless of what exception
class that was, even though I have had to go through some hoops to preserve
it.

however, it looks like this is not an option, so I think the best option is
to just wrap it in one of my own making

Andy
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top