Atlanta Custom Software Development 

 
   Search        Code/Page
 

User Login
Email

Password

 

Forgot the Password?
Services
» Web Development
» Maintenance
» Data Integration/BI
» Information Management
Programming
  Database
Automation
OS/Networking
Graphics
Links
Tools
» Regular Expr Tester
» Free Tools

Add exception tracing with one line of code

Total Hit ( 3950)

Rate this article:     Poor     Excellent 

 Submit Your Question/Comment about this article

Rating


 


At times you want to keep a log of all the exception occurred in your application, including those that are correctly caught by a Catch block. At first you might believe that you need to add a call to the LogException procedure from each and every Catch block, which is clearly a nuisance:

Click here to copy the following block
Try
  ' do something
  ' ...
Catch ex As FileNotFoundException
  Debug.WriteLine(ex.Message)
  ' ...
Catch ex As DivisionByZeroException
  Debug.WriteLine(ex.Message)
  ' ...
Catch ex As Exception
  Debug.WriteLine(ex.Message)
  ' ...
End Try

Visual Basic .NET supports the When clause in exception filters, which makes this task much simpler. As a matter of fact, you just need one single statement for each Try block that you want to keep under observation:

Click here to copy the following block
Try
  ' do something
  ' ...
Catch ex As Exception When LogException(ex)

Catch ex As FileNotFoundException
  ' ...
Catch ex As DivisionByZeroException
  ' ...
Catch ex As Exception
  ' ...
End Try

The LogException is a function defined in a Module block, that does the actual logging and always returns False:
Function LogException(ByVal ex As Exception) As Boolean
  Debug.WriteLine(ex.Message)
  Return False
End Function

Here's how it works. The Catch clause soon after the Try block traps a generic Exception object, and therefore matches all exceptions, so Visual Basic evaluates the When clause to see whether its expression returns True. At this point the LogException function is invoked, so you have an opportunity to log the exception somewhere. Just remember that you must return False so that VB.NET then ignores this Catch and passes to the ones that follow it, where the exception is actually processed.


Submitted By : Nayan Patel  (Member Since : 5/26/2004 12:23:06 PM)

Job Description : He is the moderator of this site and currently working as an independent consultant. He works with VB.net/ASP.net, SQL Server and other MS technologies. He is MCSD.net, MCDBA and MCSE. In his free time he likes to watch funny movies and doing oil painting.
View all (893) submissions by this author  (Birth Date : 7/14/1981 )


Home   |  Comment   |  Contact Us   |  Privacy Policy   |  Terms & Conditions   |  BlogsZappySys

© 2008 BinaryWorld LLC. All rights reserved.