A
Andy Fish
Dear C# gurus. consider the folowing code:
try {
try {
throw new Exception("a");
} finally {
throw new Exception("b");
}
} catch (Exception e) {
Debug.WriteLine(e);
}
When I tried this in visual studio 2008 (.net 3.5), the exception
caught by the exception handler is "b". Section 23.3 of the ECMA 334
C# language specification helpfully says "The behavior of uncaught
exceptions that occur during finalizer execution is unspecified."
If some unexpected event happens, I would expect the exception seen by
the outside world would be the original one, not something that
happened as a side effect of clearing up. This is what java does by
design and I don't see any justification for the current behaviour.
OTTOMH the only way i can think of to solve this problem is something
like this:
bool exceptionInTryBlock = true;
try
{
main body of try block
exceptionInTryBlock = false;
} finally {
try {
} catch (Exception e) {
if (!exceptionInTryBlock) {
throw e;
}
}
}
but I need to do this for every try/finally block in the code (and
even then I get hit by the bug that rethrowing an exception wipes out
the original stack trace).
Since C# is designed to be used for production applications, surely
someone else has solved this problem before? any clues much
appreciated please. am I doing something fundamentally wrong in my
whole approach to exception handling?
try {
try {
throw new Exception("a");
} finally {
throw new Exception("b");
}
} catch (Exception e) {
Debug.WriteLine(e);
}
When I tried this in visual studio 2008 (.net 3.5), the exception
caught by the exception handler is "b". Section 23.3 of the ECMA 334
C# language specification helpfully says "The behavior of uncaught
exceptions that occur during finalizer execution is unspecified."
If some unexpected event happens, I would expect the exception seen by
the outside world would be the original one, not something that
happened as a side effect of clearing up. This is what java does by
design and I don't see any justification for the current behaviour.
OTTOMH the only way i can think of to solve this problem is something
like this:
bool exceptionInTryBlock = true;
try
{
main body of try block
exceptionInTryBlock = false;
} finally {
try {
} catch (Exception e) {
if (!exceptionInTryBlock) {
throw e;
}
}
}
but I need to do this for every try/finally block in the code (and
even then I get hit by the bug that rethrowing an exception wipes out
the original stack trace).
Since C# is designed to be used for production applications, surely
someone else has solved this problem before? any clues much
appreciated please. am I doing something fundamentally wrong in my
whole approach to exception handling?