Search
Thursday, December 20, 2001 ..:: Home ::.. Register  Login
   Calendar  
     
  
   Search  
     
  
   Disclosure  
     
  
   TechTidBits (Blog)  

Exceptional Series (1/3): Throwing exceptions in different ways

Apr 3

Written by:
Friday, April 03, 2009 12:32 PM  RssIcon

Exceptions are by their very nature, very exceptional (haha pun intentional)! :>  There are quite a few different ways of throwing and catching them.  I hope you enjoy this short series on exception handling (this is part 1 of 3).

This is a three part Exception handling series on:

1) Throwing/catching in different ways

2) Performance impacts and

3) Alternative error handling mechanism.

This first blog is about different ways of throwing and catching exceptions (sample solution is available).

Throwing/catching in Differen Ways

I'm assuming you know what Exceptions are and have used them in the past.  Have you ever tried to enumerate just how many different ways there with throwing and catching Exceptions?  I didn't until looking at material for this blog article.  Turns out there quite a few.  In the sample solution I've created, take a look at 1-ExceptionHandlingDifferentWays and you'll find six different ways!  This is a standard Console app (trying to focus on exceptions and not WinForms) that has:

  • a Program class which serves as the mainline to start everyrthing off (and time it too)
  • an Nhl class which is the focus of the throwing/catching exceptions material
  • and lastly WrongTeamWinningException class which extends ApplicationException to show all this works for custom exceptions as built in .NET exceptions

What's the big deal with Exceptions?  They tell your users and eventually you, the developer what happened, what went wrong and potentially gives you a HUGE jump on where to go looking to fix the problem!  AAAAHHHHH That last statement is a big problem with the MANY different ways to throw/catch Exceptions.  In MOST of the C# training material I've read/looked at/visited on the web/etc they talk about catching an exception and either "doing something about it" but never themselves putting code to do anything, or they just catch the generic Exception and.....well......leave it up to you to figure out the rest.  HHHMMM that just sucks IMHO!  Now for the biggest problem!  Have you EVER tried to debug one of THOSE exceptions?  If you said IMPOSSIBLE you're right!  They're throwing exceptoins the easy way, not the right way.  I would like to show you the right way.

Let's start off with the simplest of classes in the solution to illustrate the debugging point, the WrongTeamWinningException.  It has two constructors which call base() and they support the many different ways to create exceptions which we'll use shortyly.

WrongTeamWinningException

Next is the Nhl class (can you tell I'm a hockey fan? :>).  This the meat of this article and to fully appreciate it, you should download the solution.  This class has two methods, PredictNextCupWinner which calls GetNextStanelyCupChampion.  Try not to focus on the method names, just that one calls the other to illustrate the stacktrace property which is invaluable to debugging!  Of the six ways to throw/catch exceptions the first FIVE, at the end of the exception, give you all the same information, which unfortuantely is grossly inadequate!  Only the last one is good enough!  I'm not saying "the last one" cause it's MY solution/idea, just that it is the right way.

The first five variations, are something like this.

Inadequate Try/Catch

This is what ALL the training material tell you to do.  So what's wrong with it?  Well, nothing, if you don't care anything about the picture of the world was AS the exception was being thrown.  At runtime, this is what you would see.

Inadequate Try/Catch at Runtime

You do get things like the exception details, line number, etc.  But what are you missing?  In this case you know everything about ONE exception.  What happens if you have multilpe exceptions occuring?  Notice how the InnerException says (null), that's key!  You know where things went wrong, but hhhmmmm you know very little else. So what's the alternative? 

Check this out!  With one small change to your code, by adding the current exception to the new exception constructor call, you are WORLDS ahead in terms of volumes of information for debugging purposes!

Better Try/Catch block constructor

WIth the simple addition of the exception variable 'e' to the constructor you're IMMEDIATELY able to see some history onto what caused the exception from happening!  At this point you've kept the stacktrace informatin intact and can interogate it to solve your problem much faster!

Better try/catch at runtime

Look at that InnerException line in the middle, you'll quickly discern the problem is iwth the InvalidOperationException that is the heart of the issue and not the WrongTeamWinningException!

Here are some other good to follow Exceptions rules:

  • never catch Exception or simple just use "catch", not catching anything and just passing it up the calling stack should be preferable to "swallowing" the generic Exception and doing nothing
  • break the first rule IF and only IF you are catching the generic Exception to do something (like logging) but ALWAYS make sure you rethrow it again with the very plain and basic "throw" statement, anything else will screw up the stacktace
  • always put the most specific exception you want to catch at the top of the catch list, if not, it'll never get reached
  • if you are using a try/catch/finally, take a look at reworking code to use a using() statement instead (hey, I didn't say refactor your code, I just said look into it)

Yes, sometimes, you do want to masquarade you exceptions or to hide them, but now that you're armed with this information, I do hope you'll only do it when you explicitly want to hide information and share your exception otherwise.  Now go grab a coffee and get coding! :>

 

Resources:

Source Code: http://www.pchenry.com:8080/svn/Blog/trunk/2009/ExceptionHandlingDifferentWays

Mauro Sant'Anna: DevTeach session on Exceptions

Mauro Sant'Anna: Interview with Andres Hejlsberg (talking about not using try/catch/finally at the same time)

stackoverflow: Proper use of try...catch

Tags:
Categories:
Location: Blogs Parent Separator TechTidBits

3 comment(s) so far...


Re: Exceptional Series (1/3): Throwing exceptions in different ways

There is a 'design/architecture' decision problem that your showing there though... you are 'assuming' that the exception that was caught has something to do with 'WrongTeamWinningException' and just automatically wrapping it. What is the exception was actually something to do with I/O (just using it as an example).

Personally, I'm not a big fan of 're-wrapping' exceptions. Generally, you should only catch exception that you 'know' (i.e. DivideByZeroException) and in this manner, you exactly what it is and possibly how to handle it (or its recovery). Catching a 'general' (aka. 'I really have no idea what just went wrong') should generally be the extreme case for the developer to log it, do some clean up and possibly abort the application (nicely). I mean, since you don't really know what went wrong, one shouldn't be continuing as they could possibly working with corrupted data. Now if the developer is expecting a possible exception to happen, then they should specifically catch it (and others if known).

Just my 2cents...

By Shane on   Sunday, April 05, 2009 7:55 PM

Re: Exceptional Series (1/3): Throwing exceptions in different ways

re assuming the exception caught has something to do with what was caught
That is why partly why I picked my own custom exception because it could be anything you wanted to catch, like an I/O exception, or a db t-sql get. The main focus on the code was to illustrate how exceptions can be thrown in multiple ways and that most of the websites talk about the ways in which, well, IMHO are not helpful to developers in the long haul.

re re-wrapping
I agree, if you're just catching and rethrowing......hhhhmmm that's a lot of work to do what .NET already does for free. So I think if you're going to bother with the effort to catch an exception, make it worth your while and do something with that information. Either correct the situation or exit, but do something.

Thanks for the feedback!

By phenry on   Sunday, April 05, 2009 8:00 PM

Re: Exceptional Series (1/3): Throwing exceptions in different ways

More information available from CaubleStone Ink (http://www.caublestoneink.com/dev/2009/04/exception-handling-basics/).

By phenry on   Friday, April 17, 2009 1:02 PM

Your name:
Gravatar Preview
Your email:
(Optional) Email used only to show Gravatar.
Your website:
Title:
Comment:
Add Comment   Cancel 
     
  
Copyright 1999-2012 by PCHenry.com   Terms Of Use  Privacy Statement