The throw statement has three general forms...
throw;
throw ex;
throw new Exception("msg" ,InnerException )
The differerences are subtle but important. If an exception object is
specified then the stack trace is captured and saved into the exception
object. If it is not specified then the stack trace is supposed to not be
captured and saved.
The first form is used to rethrow an existing exception, such as your code
snippet is intended to do. It is supposed to preserve the stack trace of the
original exception, but in the 1.1 framework there is a bug that actually
resets the stack trace so that catch blocks higher up the call stack will
get a stack trace that begins at the line where the throw statement occurs
rather then where the exception actually occurred. This form can ONLY be
used within the catch block itself...if you call other methods inside the
catch block then this form is not available to them (the C# compiler will
flag it as an error).
The second form rethrows the original exception but explicitly
(deliberately) resets the stack trace to start at the line of the throw
statement. Since this form does not add any useful information and
deliberately obscures the origin of the exception it has little to recommend
its use.
The third form is usually referred to as a catch-wrap-throw. The original
exception is wrapped up in a new exception object. The stack trace is
captured into the new exception object and the original exception is chained
to the new one via the inner exception so that a complete stack trace is
available...
I usually prefer the 3rd form as you can add context information to the
exception and it preserves the original exception.
The use of the throw statement is unrelated to the type of exception that is
thrown...you can throw types defined in system libraries or you can define
and throw custom exceptions.
You should also be aware that methods that you invoke inside of a catch
block can throw its own exception, which may be completely unrelated to the
original exception. In your example, the call to
ExceptionPolicy .HandleExceptio n(...) can itself call use either of the
forms:
throw ex;
throw new Exception();
Exceptions thrown within a catch block cause the remainder of the code in
the catch block to be skipped and a new exception handling process (walk the
stack looking for a catch block) will begin.
"Arjen" <bo*****@hotmai l.com> wrote in message
news:dc******** **@news6.zwoll1 .ov.home.nl...
Hi,
I'm reading the enterprise library documentation and there I see the throw
statement.
try
{
// run code
}
catch(Exception ex)
{
bool rethrow = ExceptionPolicy .HandleExceptio n(ex, "Logging Policy");
if (rethrow)
throw;
}
Can somebody tell what the throw statement does?
How can I use it? In what situation? Etc.
Thanks!
Arjen