c# "finally" block that only runs on exceptions - c#

Edit: I have looked at the answers code: NONE of them do what I want (I've checked). It would seem that there is no way to do what I want in native c#. I guess that's not a disaster just a shame given that .NET does support it (see accepted answer).
Thanks all.
I have c# code (part of a test framework that will never be run except under a debugger) like this who's point it to avoid actually catching the exception as that makes debugging the code in the unwound part of the stack a royal pain.
Bool bad = true;
try
{
MightThrow();
bad = false;
}
finally
{
if(bad) DoSomeLoggingOnFailure();
//// Does not catch!!!!
//// exception continues to unwind stack.
//// Note that re throwing the exception is NOT
//// the same as not catching it in the first place
}
is their a better way to do this?
A solution would have to behave exactly like that under the debugger with regards to un-caught exceptions. It would have to result in the only one first chance exception and the debugger breaking at the point that the exception was originally thrown, not in a catch block.
Specifically I need the debugger on un-caught exceptions to stop a in side MightThrow.
The following doesn't work because it fails to have the debugger break in the correct place
try { ... } catch { throw; }
And this doesn't work because it loses stack info (and also breaks in the wrong place).
try { ... } catch(Exception e) { throw e; }
I known that in D I could use a scope(failure) block

So, in .NET what you're asking for is theoretically possible, but it's not going to be easy.
CIL actually defines five types of exception handling block! The try, catch and finally ones you're used to in C#, and two others:
filter - similar to a catch block but can run arbitrary code to determine whether it wants to handle the error, rather than just matching on type. This block has access to the exception object, and has the same effect on the exception stack trace as a catch block.
fault - similar to a finally block, however it is only run when an exception occurs. This block does not have access to the exception object, and has no effect on the exception stack trace (just like a finally block).
filter is available in some .NET languages (e.g. VB.NET, C++/CLI) but is not available in C#, unfortunately. However I don't know of any language, other than CIL, that allows the fault block to be expressed.
Because it can be done in IL means not all is lost, though. In theory you could use Reflection.Emit to dynamically emit a function that has a fault block and then pass the code you want to run in as lambda expressions (i.e. one for the try part, one for the fault part, and so on), however (a) this isn't easy, and (b) I'm unconvinced that this will actually give you a more useful stack trace than you're currently getting.
Sorry the answer isn't a "here's how to do it" type thing, but at least now you know! What you're doing now is probably the best approach IMHO.
Note to those saying that the approach used in the question is 'bad practice', it really isn't. When you implement a catch block you're saying "I need to do something with the exception object when an exception occurs" and when you implement a finally you're saying "I don't need the exception object, but I need to do something before the end of the function".
If what you're actually trying to say is "I don't need the exception object, but I need to do something when an exception occurs" then you're half way between the two, i.e. you want a fault block. As this isn't available in C#, you don't have an ideal option, so you may as well choose the option that is less likely to cause bugs by forgetting to re-throw, and which doesn't corrupt the stack trace.

How about this:
try
{
MightThrow();
}
catch
{
DoSomethingOnFailure();
throw; // added based on new information in the original question
}
Really, that's all you did. Finally is for things that must run regardless of whether an exception occurred.
[Edit: Clarification]
Based on the comments you've been mentioning, you want the exception to continue being thrown without modifying its original stack trace. In that case, you want to use the unadorned throw that I've added. This will allow the exception to continue up the stack and still allow you to handle part of the exception. Typical cases might be to close network connections or files.
[Second edit: Regarding your clarification]
Specifically I need the debugger on
un-caught exceptions to stop at the
original point of the throw (in
MightThrow) not in the catch block.
I would argue against ever breaking a best-practice (and yes, this is a best-practice for partially handling exceptions) to add some minor value to your debugging. You can easily inspect the exception to determine the location of the exception throw.
[Final edit: You have your answer]
kronoz has thoughtfully provided you with the answer you sought. Don't break best practices -- use Visual Studio properly! You can set Visual Studio to break exactly when an exception is thrown. Here's official info on the subject.
I was actually unaware of the feature, so go give him the accepted answer. But please, don't go trying to handle exceptions in some funky way just to give yourself a hand debugging. All you do is open yourself up to more bugs.

If you're interested in the debugger simply stopping precisely where the exception occurred then have you considered first-chance exceptions?
If you open Tools|Exceptions then tick the Common Language Runtime Exceptions box, the debugger will stop at the point of exception regardless of any try/catch/finally blocks.
Update: You can specify the precise exception you wish to catch by expanding the [+] tree in the Exceptions dialog. Though of course it will fire every time any exception of the specified type[s] occur[s], you can switch it on and off at will even in the middle of a debugging session, so with judicious use of breakpoints you can get it to do your bidding. I used it successfully to get around the 'target of an invocation has thrown an exception' ball ache originating from using reflection to instantiate objects. Very useful tool in such circumstances. Also note the locals and stack trace should be firmly available as far as I recall (just did a quick test and they are available), so no problems there.
Of course if you want to log things then that is outside the scope of an IDE debugger; and in which case first-chance exceptions won't help you!
Give it a go at least; I found them very useful and they might be more appropriate for your issue than you think.

What's wrong with:
try
{
MightThrow();
}
catch
{
DoSomthingOnFailure();
throw;
}

For code that should only run on exceptions, use the catch block:
try
{
MightThrow();
}
catch (Exception ex)
{
// this runs only when there was an exception
DoSomthingOnFailure();
// pass exception on to caller
throw;
}
finally
{
// this runs everytime
Cleanup();
}

This is what you want. It will only call this method when an error occurs, and the "throw" statement will re-throw the exception with the callstack intact.
try
{
MightThrow();
}
catch
{
DoSomthingOnFailure();
throw;
}

A "finally" block that runs only on failure is called "catch" (with no parameters). :-)
Now, there is a small caveat. If you want to have a specialised "catch" case for a particular exception type and have a generic "catch" that works for all exceptions, you'll have to do a bit of a custom logic.
Thus, I would do something like:
try
{
MightThrow();
}
catch(MyException ex)
{
// Runs on MyException
MySpecificFailureHandler()
// Since we have handled the exception and can't execute the generic
// "catch" block below, we need to explicitly run the generic failure handler
MyGenericFailureHandler()
}
catch
{
// Runs on any exception hot handled specifically before
MyGenericFailureHandler()
// If you want to mimic "finally" behavior and propagate the exception
// up the call stack
throw;
}
finally
{
// Runs on any failure or success
MyGenericCleanupHandler();
}

Every example so far is losing the original StackTrace according to my tests. Here's a solution that should work for you.
private static void PreserveStackTrace(Exception exception)
{
MethodInfo preserveStackTrace = typeof(Exception).GetMethod("InternalPreserveStackTrace",
BindingFlags.Instance | BindingFlags.NonPublic);
preserveStackTrace.Invoke(exception, null);
}
try
{
MightThrow();
}
catch (Exception ex)
{
DoSomethingOnFailure();
PreserveStackTrace(ex);
throw;
}

How about only catching an exception that "MightThrow" does not throw?
Bool bad = true;
try
{
MightThrow();
bad = false;
}
catch (SomePrivateMadeUpException foo)
{
//empty
}
finally
{
if(bad) DoSomeLoggingOnFailure();
}

Let me recap your requirements the way I understand them:
You want some code that is run only when an exception is generated, in order to do some logging.
You want to run your test framework under debugger and break at the point at which the exception is thrown.
To meet your first requirement, you should write the code the way everybody suggested - using parameterless catch and throw.
To meet your second requirement while using the parameterless catch, you could configure your debugger to break when an exception is throw, not only when there's an unhandled exception. I suspect you know how to do it, but I'll put it here for answer completeness: in VS you can do that in Debug -> Exception -> Common Language Runtime Exceptions -> check the Thrown checkbox.
If you know that your app throws a lot of handled exceptions, that might not be an option for you. At that point, your only choice left to meet your first requirement is to either write the code to use finally for exception logging purposes or look into the direct IL emitting route as Greg Beech suggests.
However, whether the finally code is being executed depends on the debugger you are using. In particular, VS will break on an unhadled exception before the finally is executed and will not let you continue. Thus, unless you detach from the process at that point, your logging code will never be executed. In other words, the second requirement will interfere with meeting the first requirement.

You could encapsulate your logic in a custom class, something like:
public class Executor
{
private readonly Action mainActionDelegate;
private readonly Action onFaultDelegate;
public Executor(Action mainAction, Action onFault)
{
mainActionDelegate = mainAction;
onFaultDelegate = onFault;
}
public void Run()
{
bool bad = true;
try
{
mainActionDelegate();
bad = false;
}
finally
{
if(bad)
{
onFaultDelegate();
}
}
}
}
And use it as:
new Executor(MightThrow, DoSomeLoggingOnFailure).Run();
Hope this helps.

Isn't this the same as:
try
{
MightThrow();
}
catch (Exception e)
{
DoSomethingOnFailure();
throw e;
}
?

You could write, or have someone write for you, a small assembly in VB.net which implements a TryFaultCatchFinally(of T) method that accepts four delegates:
TryMethod -- An Action(of T) to perform the "Try" block.
FaultMethod -- A Predicate(Of T, Exception) which, if an exception occurs, will be called before any "finally" blocks run; if it returns true the Catch block will run--otherwise it won't.
CatchMethod -- An Action(Of T, Exception) to be performed if an exception had occurred and FaultMethod returned true; happens after "finally" blocks run.
FinallyMethod -- An Action(OF T, Exception, Boolean) to be performed as a "Finally" block. The passed-in exception will be null if TryMethod ran to completion, or will hold the exception that caused it to exit. The Boolean will be true if the exception was caught, or false otherwise.
Note that when the FaultMethod is executed, one may be able to examine the state of objects that caused the exception, before such state is destroyed by Finally blocks. One must use some care when doing this (any locks that were held when the exception was thrown will continue to be held) but the ability may still sometimes be handy, especially when debugging.
I'd suggest the routine look something like:
Shared Sub TryFaultCatchFinally(Of T)(ByVal TryProc As Action(Of T), _
ByVal FaultProc As Func(Of T, Exception, Boolean), _
ByVal CatchProc As Action(Of T, Exception), _
ByVal FinallyProc As Action(Of T, Exception, Boolean), _
ByVal Value As T)
Dim theException As Exception = Nothing
Dim exceptionCaught As Boolean = False
Try
TryProc(Value)
theException = Nothing
exceptionCaught = False
Catch Ex As Exception When CopyExceptionAndReturnFalse(Ex, theException) OrElse FaultProc(Value, Ex)
exceptionCaught = True
CatchProc(Value, Ex)
Finally
FinallyProc(Value, theException, exceptionCaught)
End Try
End Sub

No, I think this is a common idiom the way you have it.
EDIT
To be clear, the "catch" then "rethrow" strategies offer the same run-time semantics, however they change the experience when the VS debugger is attached. Tooling and maintenance is important; debugging often requires you to 'catch all first-chance exceptions' and if you end up with lots of 'spurious' first-chance exceptions due to catch-then-rethrow in your code, it really hurts the ability to debug the code. This idiom is about interacting well with the tooling, as well as clearly expressing the intent (you don't want to 'catch', decide can't handle, and rethrow, instead you just want to log that an exception did happen but let it pass on by).

Have you considered using the DebuggerStepThrough attribute?
http://msdn.microsoft.com/en-us/library/system.diagnostics.debuggerstepthroughattribute.aspx
[DebuggerStepThrough]
internal void MyHelper(Action someCallback)
{
try
{
someCallback();
}
catch(Exception ex)
{
// Debugger will not break here
// because of the DebuggerStepThrough attribute
DoSomething(ex);
throw;
}
}

With exception filters added in C# 6, one option is to make use of a false returning exception filter, like so:
void PerformMightThrowWithExceptionLogging()
{
try
{
MightThrow();
}
catch (Exception e) when (Log(e))
{
// Cannot enter here, since Log returns false.
}
}
bool Log(Exception e)
{
DoSomeLoggingOnFailure(e);
// Return false so the exception filter is not matched, and therefore the stack is kept.
// This means the debugger breaks where the exception actually happened, etc.
return false;
}
See https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/try-catch for more details on exception filters.

try
{
MightThrow();
}
catch
{
DoSomethingOnFailure();
}

Related

position of the try catch statement

I have some code that currently looks somewhat like this:
public void MainFunction()
{
try
{
SomeProblemFunction();
}
catch
{
AllFineFunction();
}
}
private void SomeProblemFunction() { ... }
private void AllFineFunction() { ... }
As you can see, I'm currently wrapping the call to SomeProblemFunction around a try statement because that function could fail (it relies on an outside web service call).
My question is this: should the try statement be a) outside the problem function (like I have it now) or b) inside the problem function?
Thanks.
Typically you want to allow your exceptions propagate up to your application boundaries. You're only going to want to do one of a few things with your exception:
Wrap it
Replace it
Let it propagate
Update
From your question it seems that you are looking for a fault tolerant solution for your web service calls. This is a more complex problem than simply "where do I put my try-catch?" You would still place your exception handling at the application boundary, but there you would implement your fault tolerance strategy. This would need to have many considerations, including asynchronously calling your web service, number of retry attempts, etc. I would suggest doing a search for web service fault tolerance.
What you have is correct; see the MSDN example:
public class ThrowTestB
{
static void Main()
{
try
{
// TryCast produces an unhandled exception.
TryCast();
}
catch (Exception ex)
{
// Catch the exception that is unhandled in TryCast.
Console.WriteLine
("Catching the {0} exception triggers the finally block.",
ex.GetType());
// Restore the original unhandled exception. You might not
// know what exception to expect, or how to handle it, so pass
// it on.
throw;
}
}
public static void TryCast()
{
int i = 123;
string s = "Some string";
object obj = s;
try
{
// Invalid conversion; obj contains a string, not a numeric type.
i = (int)obj;
// The following statement is not run.
Console.WriteLine("WriteLine at the end of the try block.");
}
finally
{
// Report that the finally block is run, and show that the value of
// i has not been changed.
Console.WriteLine("\nIn the finally block in TryCast, i = {0}.\n", i);
}
}
// Output:
// In the finally block in TryCast, i = 123.
// Catching the System.InvalidCastException exception triggers the finally block.
// Unhandled Exception: System.InvalidCastException: Specified cast is not valid.
}
As a rule of thumb I try and build code that focuses try catches to the exact spot the problem may occur.
That said both of your solutions are correct.
If it were my code I would do this
public void MainFunction()
{
try
{
SomeProblemFunction();
}
catch(Exception e)
{
Messagebox.Show(e.Message);
}
}
private void SomeProblemFunction() {
try{
web call
}
catch{
throw a specific exception related to this spot
}
}
private void AllFineFunction() { ... }
With this method you can easily create applications that handle a slew of very accurate exceptions
A fine question, I think. I'll attempt an answer.
If you want to recover within SomeProblemFunction, then it would make perfect sense to move the try...catch inside of that method. If, however, you are comfortable saying that if anything fails in SomeProblemFunction, then the whole thing is a failure, then keep it as you have it now and recover in (or throw from) MainFunction.
Thanks to the comment below, I'm adding some clarity. Depending on the specific exception that is being thrown within SomeProblemFunction, you may not have the ability to recover within that method. If you have a mixture of recoverable and non-recoverable, then it would be prudent to have the try...catch in both places.
The most important thing is that you NEVER catch an exception from which you cannot recover without throwing it on after doing your thing. It's tempting to add big broad catches (catch (Exception)) to avoid your app crashing during development, but it is never worth it. If those things make it into your production code, you've introduced a problem-solving and debugging nightmare.
In my opinion, there is no straight answer for this. The try catch is used to handle the exceptions that may occur. If your exception handling code is going in the main function then you should have the try catch in the main function. If your exception handling code in the problem function then you should add it to the problem function.
My preference though is to put it in both functions. If you put the try catch in the problem function, you can throw the exception and catch it in the main function. This always appear to other developers that the exception was thought of in that function and not missed handling it by mistake.
This depends on how severe this web service call failure would be.
Is it a failure that would prevent further processing of your code to run? If so, have no try/catch here, allowing it to propagate up to the guy who needs to know that this web service call failed. Optionally, you could still catch and throw a new exception with some more meaningful Exception type/ details.
Do you simply just want to re-try the web service call again if it doesn't work? IF so, then you have the try in the correct place; you just need to add a loop.
Is it not a big deal if this web service call fails? e.g. - will the rest of your code work OK? (I've found this to be uncommon). If so, leave the try/catch where it is, and log the error somewhere so that you're alerted.

Uniform handling of many exceptions

In my current project, i am interacting with some 3rd party middleware that throws many different types of exceptions (around 10 exceptions or more).
My library that is using the 3rd party has a few methods, each one interacts with the 3rd party, however needs to be protected from the same set of 10 or more exceptions.
What i currently have is something like this in every method of my library:
try
{
// some code
}
catch (Exception1 e)
{
}
catch (Exception2 e2)
{
}
...
catch (ExceptionN eN)
{
}
The number of exceptions may increase as well.
How can i reduce the code duplication and uniformly handle all exceptions in a single place?
suppose that the handling in each method in my code is the same.
I would start by catching the base Exception type and then filtering with a white-list:
try
{
// Code that might throw.
}
catch (Exception e)
{
if(e is Exception1 || e is Exception2 || e is ExceptionN)
{
// Common handling code here.
}
else throw; // Can't handle, rethrow.
}
Now if you want to generalize the filter, you can write an extension:
public static bool IsMyCustomException(this Exception e)
{
return e is Exception1 || e is Exception2 || e is ExceptionN;
}
and then you can just use:
if(e.IsMyCustomException())
{
// Common handling code here.
}
else throw;
You can generalize the handler with a simple method:
private void HandleCustomException(Exception e)
{
// Common handling code here.
}
If you want to generalize the entire try-catch block, you're probably best off injecting a delegate into a method that wraps the operation, as mentioned by #vc 74.
You can either use a global exception handler, the implementation depends on your project type (ASP.net -> global.asax, WPF -> App.xaml...)
Or use something like the following :
private static void HandleExceptions(Action action)
{
try
{
action();
}
catch (Exception1 e)
{
}
catch (Exception2 e2)
{
}
...
catch (ExceptionN eN)
{
}
}
which can be invoked the following way:
HandleExceptions(() => Console.WriteLine("Hi there!"));
If an exception was thrown during the Console.WriteLine execution, it would then be handled by your exception handling logic
Note that the code to execute might also modify external values:
int x = 2;
HandleExceptions(() => x = 2 * x);
If you prefer anonymous methods:
var x = 2;
HandleExceptions(delegate()
{
x = x * 2;
});
I recommend using the Enterprise Library 5.0 Exception handling block. Basically, you define multiple exception types, categories and exception handlers that handle specific exception types. Ideally, you would define the exception type, hook it up to a formatter and then report the exception using the Logging block.
You can read all about it here...
how about use one function to handle these Exceptions:
try
{
//Some code here
}
catch(Exception e)
{
if(!ErrorHandler(e))
return null; //unhandled situation
}
private bool ErrorHandler(Exception e)
{
switch(e)
{
case Exception1:
//Handle the exception type here
return true;
case Exception2:
//Handle another exception type here
return true;
}
return false;
}
There are some semantic differences between catching and rethrowing an exception, versus not catching it. Exception filters are therefore very useful, since they allow one to e.g. "Catch Ex As Exception When IsNiceException(Ex)". Unfortunately, the only way to use them within a C# program is to use a DLL to wrap the necessary functionality (the DLL itself could be written in vb or some other language). A typical pattern might be something like:
TryWhenCatchFinally(
() => {trycode;},
(Exception ex) => {codeWhichReturnsTrueForExceptionsWorthCatching;},
(Exception ex) => {codeToHandleException;},
(ExceptionStatus status, Exception ex) => {finallyCode;});
The ExceptionStatus parameter to the "finally" code would be an enumeration saying whether (1) no exception occurred, (2) an exception occurred, but was handled, (3) an exception occurred and was handled, but another exception was thrown, or (4) an exception occurred but CodeWhichReturnsTrueForExceptionsWorthCatching returned false; (5) an exception occurred which was not handled within trycode, nor handled by this block, but trycode completed anyhow (a rare situation, but there are ways it can happen). The Ex parameter will null in the first case, and contain the appropriate exception in others--potentially useful information to have if an exception occurs while processing the finally block (stifling an exception that occurs in a finally block may be bad, but if the earlier exception isn't logged or lost before the new exception escapes, all data from the earlier exception will generally be lost; if the same condition which caused the earlier exception caused the later one, the earlier exception might have more useful information about what went wrong).
BTW, a few notes with this pattern:
The code that decides whether to catch an exception will run before nested finally blocks execute; it may capture useful data for logging (the fact that finally blocks haven't run may make available for logging information which would get destroyed by nested finally blocks), but actual cleanup should typically be done after finally blocks have run.
At present, it seems like exceptions that would escape from filters get stifled, but I'm not sure that behavior is guaranteed. Operations which might leak exceptions should probably not be done within filters.
If the "trycode" contains a try-finally block that's nested within a try-catch block, an exception which occurs in the "try" part of that try-finally block is not handled by the TryCatchWhenFamily nor any nested scope, but is handled by an outer block, and the processing of the inner try-finally block throws an exception which the inner try-catch block handles, the exception which the outer block had decided it was going to catch might disappear without ever being caught. If the TryWhenCatchFinally method is coded to detect this condition, it could let its finally block code know about that (the finally block may or may not want to do anything about the condition, but it should probably at minimum be logged).

Annotating Exceptions with extra information without catching them

Exceptions sometimes occur. When they do, they're logged and later analyzed. The log obviously contains the stack-trace and other global information, but often crucial context is missing. I'd like to annotate an exception with this extra information to facilitate post-mortem debugging.
I don't want to try{...}catch{... throw;} since that counts as catching an exception and that makes debugging harder (during development I'd like the app to stop and the debugger to react when the original exception is thrown, and not when the outermost uncaught exception is). First-chance exception handlers aren't a workaround since there are unfortunately too many false positives.
I'd like to avoid excessive overhead in the normal, non-exceptional case.
Is there any way to store key pieces of context (e.g. filename being processed or whatever) in an exception in a way that doesn't catch the exception?
I am taking a shot at this building off of Adam's suggestion of Aop. my solution would be Unity rather than postsharp and the only question I would have is whether the exception is being caught inside of invoke, which it likely is...
public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext)
{
//execute
var methodReturn = getNext().Invoke(input, getNext);
//things to do after execution
if (methodReturn.Exception != null)
methodReturn.Exception.Data.Add("filename", "name of file");
return methodReturn;
}
}
There is nothing wrong with the following pattern:
try
{
// Do Something
}
catch (GeneralException ex)
{
throw new SpecificException(
String.Format("More specifics ({0}) in message", someData),
moreContext,
new {even, more, context},
ex);
}
This is precisely the pattern to use, for instance, when the "Do Something" is to, say, open a file of some kind. The "SpecificException" might be "can't read configuration file".
I would not use AOP to catch the exceptions. Instead I would use the interception class to LOG the exception + all arguments to the method that threw the exception. And then let the original exception be thrown again

Catch All (handled or unhandled) Exceptions

I want to catch all exceptions raised (handled or unhandled) to log them. for unhandled i use ThreadExceptionEventHandler and UnhandledExceptionEventHandler but i want to catch and exceptions that are in try catch block with or without (Exception e). It's possible to inherit the exceptions class to create a general event?
Starting from Windows XP you can get notified about every raised exception, even before it's known to be handled or not.
This is available via so-called "vectored" exception handling, which is actually a little addition to the standard structured exception handling.
Call AddVectoredExceptionHandler to add your own handler. You'll get called right after the exception is raised, either by explicit throw/__CxxThrowException/RaiseException or implicitly by the processor (access violation or etc.)
You can log the exception in your handler (produce stack dump for instance), and return EXCEPTION_CONTINUE_SEARCH.
Inheriting from Exception to provide your own Exception class would work fine for exceptions you generate in your code, and you could use the inner exception constructor to carry built in exceptions up the chain.
If you were goig to try that, you'd need to replace all of your exception handling code, and probably add a chunk more as well. I don't think it'd be substantially better than Peter McG's approach, but it might allow you different options when preserving & examining the original exceptions and re-throwing, for example keeping a record of whether it has already been logged lower down the chain.
Just to be explicit, it is possible to use:
catch (Exception e)
{
log(e);
throw;
}
which will rethrow the original exception.
Sounds like you've got the Unhandled Exceptions as covered as possible, for handled exceptions can't you just eventually...
catch (Exception e) {}
and call the same logging function with the instance.
If not and you really must have some instances where you have a catch but without catching an instance you can use...
catch { throw; }
to re-throw the exception to be eventually caught and logged as an un-handled exception.
C++ allows for catch(...) which catches all exceptions but doesn't really allow to analyze them in depth. (see using catch(...) (ellipsis) for post-mortem analysis )
I'm not sure if it will work in C# though.
No, thats not possible.
The only way this would be possible is using the debugging APIs (the managed version is named mdbg)
There's no way to catch an already caught exception except, may be, working with AddVectoredExceptionHandler.
Having said that, you can use a catch-and-rethrow approach:
catch(Exception e) {
Logger.Log(e);
throw;
}
or
catch(Exception e) {
bool rethrow = LoggerStrategy.Log(e);
if(rethrow) { throw; }
}
Better still, use the Logging Application Block.

Thoughts on try-catch blocks

What are your thoughts on code that looks like this:
public void doSomething()
{
try
{
// actual code goes here
}
catch (Exception ex)
{
throw;
}
}
The problem I see is the actual error is not handled, just throwing the exception in a different place. I find it more difficult to debug because i don't get a line number where the actual problem is.
So my question is why would this be good?
---- EDIT ----
From the answers it looks like most people are saying it's pointless to do this with no custom or specific exceptions being caught. That's what i wanted comments on, when no specific exception is being caught. I can see the point of actually doing something with a caught exception, just not the way this code is.
Depending on what quality you are looking at it is not throwing the exception in a different place. "throw" without a target rethrows the exception which is very different from throwing an exception. Primarily a rethrow does not reset the stack trace.
In this particular sample, the catch is pointless because it doesn't do anything. The exception is happily rethrown and it's almost as if the try/catch didn't exist.
I think the construction should be used for handling the exceptions you know you will be throwing inside your code; if other exception is raised, then just rethrow.
Take into account that
throw;
is different than
throw ex;
throw ex will truncate the stack to the new point of throwing, losing valuable info about the exception.
public void doSomething()
{
try
{
// actual code goes here
}
catch (EspecificException ex)
{
HandleException(ex);
}
catch (Exception ex)
{
throw;
}
}
It wouldn't be, ideally the catch block would do some handling, and then rethrow, e.g.,
try
{
//do something
}
catch (Exception ex)
{
DoSomething(ex); //handle the exception
throw;
}
Of course the re-throw will be useful if you want to do some further handling in the upper tiers of the code.
Doing something like that is fairly meaningless, and in general I try not to go down the road of doing meaningless things ;)
For the most part, I believe in catching specific types of exceptions that you know how to handle, even if that only means creating your own exception with more information and using the caught exception as the InnerException.
Sometimes this is appropriate - when you're going to handle the exception higher up in the call stack. However, you'd need to do something in that catch block other than just re-throw for it to make sense, e.g. log the error:
public void doSomething()
{
try
{
// actual code goes here
}
catch (Exception ex)
{
LogException (ex); // Log error...
throw;
}
}
I don't think just rethrowing the error would be useful. Unless you don't really care about the error in the first place.
I think it would be better to actually do something in the catch.
You can check the MSDN Exception Handling Guide.
I've seen instances where generic exceptions are caught like this and then re-packed in a custom Exception Object.
The difference between that and what you're saying is that those custom Exception objects hold MORE information about the actual exception that happened, not less.
Well for starters I'd simply do
catch
{
throw;
}
but basically if you were trapping multiple types of exceptions you may want to handle some locally and others back up the stack.
e.g.
catch(SQLException sex) //haha
{
DoStuff(sex);
}
catch
{
throw;
}
Depends on what you mean by "looks like this", and if there is nothing else in the catch block but a rethrow... if that's the case the try catch is pointless, except, as you say, to obfuscate where the exception occurred. But if you need to do something right there, where the error occurred, but wish to handle the exception furthur up the stack, this might be appropriate. But then, the catch would be for the specific exception you are handl;ing, not for any Exception
Generally having exception handling blocks that don't do anything isn't good at all, for the simple reason that it prevents the .Net Virtual Machine from inlining your methods when performance optimising your code.
For a full article on why see "Release IS NOT Debug: 64bit Optimizations and C# Method Inlining in Release Build Call Stacks" by Scott Hanselman

Categories

Resources