Sneaky Exception Tricks in VB.NETSo, 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!