by via LA.NET [EN] on 12/2/2008 10:33:25 AM
While I was reading the Essential Windows Communication Foundation book (from Addision Wesley), I found the following code (on a transaction required for a WCF service context):
[OperationBehavior(TransactionScopeRequired = true, TransactionAutoComplete = true)] public void Transfer( String from, String to, double amount){ try { Withdraw(from, amount); Deposit( to, amount); } catch(Exception ex){ throw ex; } }
Lets not even talk about why using the Exception type in a try/catch is bad (though I accept its usage in a book, but only after seeing a justification of why you should not use it in production code)…instead, lets concentrate on what is happening inside the catch block…see anything wrong there? I hope so! You should never re-throw an exception like that. In my opinion, you’ve got 2 options here:
1. You’re “important” in the stack chain and then you’ll want to wrap that exception with your own specific exception type (for isntance, NHibernate does something like this and wraps ADO.NET exceptions with its own exception type). Here’s what I mean:
catch(Exception ex ) { //btw, don’t catch the Exception type //do something here…probably log it throw new MyException(ex); }
2. You’re not significant, so you can just rethrow that exception after logging:
catch(Exception ex ) { //btw, don’t catch the Exception type //do something here…probably log it throw; //see? no ex here! }
Ok, so why is this important? Because when you re-throw the exception by using technique shown in point 2, you will be preserving the stack trace. When you do it like in the original code, the stack trace that the client will see ends up in your catch block. Probably not what you’ll want in most scenarios!
Do notice that technique 1 will also preserve the stack chain since you’re passing the exception as the inner exception of the new exception you’re throwing. Both of these options are really better than the one shown on the initial code.
I’m only writing this here because I was under the impression that this info should be well know by now, but it seems like I’m wrong…Do keep in mind that it’s not my intent to trash on this book (I’m still on page 211, but I’m liking it so far), but I was a little but surprised by seeing this code there (as always, I’ll put a review after ending it).
Original Post: Re-throwing exceptions
The content of the postings is owned by the respective author. CSharpFeeds is not responsible for the contents of the postings. This site is automatically generated and cannot be reviewed for abusive content. If you find abusive content on CSharpFeeds, please contact us. Designated trademarks and brands are the property of their respective owners. All rights reserved.