Alone In The Database

Thursday, January 11, 2007

 
Sneaky Exception Tricks in VB.NET

So, I've been slowly going through the book Visual Basic 2005: The Language by Francesco Balena... I think he's a great speaker and writer, and this book certainly continues that opinion of him.

Just in the third chapter on "The Basics" I got a great tip. I thought it was worth showing the tip in hopes it makes more people go buy his book. Notice my link is not an "Amazon Affiliate" or whatever link - I won't get anything if you click or buy. I just like the author and the book.

So, this concerns exceptions. A nice trick is that you can use the WHEN clause in a CATCH clause to always log each exception even though you have multiple catch blocks. See this example:

Try
'do something
'...
Catch ex as Exception When LogException(ex)
'no code here
Catch ex as FileNotFoundException
'real code here as needed
Catch ex as DivideByZeroException
'real code here as needed
Catch ex as Exception
'real code here as needed
End Try

So, since your first CATCH block catches "Exception" it should catch ALL exceptions right? So the WHEN is always evaluated...

So, you create the LogException method as follows:

public function LogException(ByVal ex as Exception) as boolean
'do your logging code here
return false
end function

SO... since you always return FALSE, the whole CATCH block "fails to catch" and so the rest of the catch blocks still have a chance to catch the exception.

Sneaky, unorthodox, but... brilliant, as far as I'm concerned!

Comments: Post a Comment

Subscribe to Post Comments [Atom]





<< Home

Archives

05/21/2006 - 05/28/2006   05/28/2006 - 06/04/2006   06/11/2006 - 06/18/2006   06/18/2006 - 06/25/2006   07/09/2006 - 07/16/2006   07/16/2006 - 07/23/2006   07/23/2006 - 07/30/2006   08/06/2006 - 08/13/2006   08/13/2006 - 08/20/2006   10/01/2006 - 10/08/2006   10/08/2006 - 10/15/2006   10/22/2006 - 10/29/2006   11/26/2006 - 12/03/2006   01/07/2007 - 01/14/2007   03/25/2007 - 04/01/2007   04/15/2007 - 04/22/2007   04/29/2007 - 05/06/2007   05/06/2007 - 05/13/2007   05/13/2007 - 05/20/2007   06/10/2007 - 06/17/2007   07/29/2007 - 08/05/2007   09/09/2007 - 09/16/2007   12/09/2007 - 12/16/2007   06/29/2008 - 07/06/2008   10/26/2008 - 11/02/2008   11/23/2008 - 11/30/2008   12/28/2008 - 01/04/2009  

This page is powered by Blogger. Isn't yours?

Subscribe to Posts [Atom]