Search - Articles
DevASP.NET for ASP.NET, VB.NET, XML and C# (C-Sharp) Developers Tuesday, March 03, 2009
Dev Articles
Search Directory
ASP.NET
VB.Net
C-Sharp
SQL Server
 

Custom Exceptions & Global Exception Handlers in VB.Net

Author: DevASP
Download Source Code : 399_VB.NET - Windows Forms- How-To Custom Exceptions.zip

This Article Defines two advanced exception mangement techniques. CustomerException, EmployeeException

Class Library

The class library defines one application class, Customer. In addition it exposes a set of custom exception class which is used to expose application defined errors. Unlike previous versions of Visual Basic (and COM which it was based upon), .NET Exceptions are fully typed removing the need for error numbers. While you can still have error numbers, it is much better to defined application exceptions which can expose a much richer array of information to the caller. In this application there is a hierarchy of exceptions. At the top is CRMSystemException for the fictitious SomeCompany CRM system. It inherits from System.Application exception (as opposed to System.SystemException which is used by Microsoft). From there, two classes inherit from it:

  • CustomerException
  • EmployeeException

There is nothing in this sample related to employees, but we wanted to show how you can have a larger product that could be made up of various modules or components. There then two more exceptions which both inherit from CustomerException:

  • CustomerNotFoundException
  • CustomerNotDeletedException

Each class exposes different levels of information and functionality. Examine the source code for more comments. Note that your exceptions classes can be named anything, but by convention they should end with the suffix Exception.

Client

The client application has a reference to the class library. Two command buttons show how to execute methods against the customer class and catch the custom exceptions. A third command button causes an unhandled exception. In addition, there is a check box labeled 'Turn on Global Exception Trap' which when checked enabled a global exception trap. When enabled, the code defined in OnThreadException will be executed instead of the default Windows Form handler. Please see the comments for more information. Because for it helps you allot.

You have to Imports some namespaces as I include in my code.

Imports external assembly that defines a Customer class, and three custom exception classes. Note the reference required via the References folder.

 

Imports SomeCompany.CRMSystem

 

Add any initialization after the InitializeComponent() call, So that we only need to set the title of the application once, we use the AssemblyInfo class (defined in the AssemblyInfo.vb file) to read the AssemblyTitle attribute.

 

Dim ainfo As New AssemblyInfo

 

'Include one region in your code.

'System.Diagnostics.DebuggerStepThrough()

'has been added to some procedures since

'they are not the focus of the demo.

'Remove them if you wish to debug the procedures.

'This code simply shows the About form

 

#Region " Standard Menu Code "

   

 

Private Sub mnuAbout_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)

 

End Sub

 

'This code will close the form.

Private Sub mnuExit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles mnuExit.Click

 

  'Close the current form

   Me.Close()

 

End Sub

 

#End Region

 

 

'Write this code against Edit Control

 

Private Sub cmdEdit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdEdit.Click

 

Dim c As Customer

 

Try

 

 Dim i As Integer = 14213

 c = Customer.EditCustomer(i)

 

 Catch exp As CustomerNotFoundException

   MessageBox.Show(exp.Message, exp.AppSource, MessageBoxButtons.OK, MessageBoxIcon.Error)

 

  Catch exp As CustomerException

    MessageBox.Show(exp.Message, exp.AppSource, MessageBoxButtons.OK, MessageBoxIcon.Error)

 

  Catch exp As Exception

   MessageBox.Show(exp.Message, exp.Source, MessageBoxButtons.OK, MessageBoxIcon.Error)

 

 End Try

 

End Sub

 

Write Function Below for Untrapped. Normally an untrapped error in Visual Basic 6.0 and earlier would result in a quick MessageBox and then our process shutting down. Windows Forms however have injected a top-level error catch between the CLR and our code.

 

 Whether or not you see their dialog depends upon three things:

 

 1) Is there an active debugger?

 2) Do you have your own exception handler in place?

 3) Have you turned JIT debugging on (set to true) in your App's config file.?

 

If an untrapped error occurs and you answered no to the above questions, then you will see the Windows Forms dialog which gives the user a chance to Continue or Quit. To see thier handler, you need to run the compiled code.

 

Private Sub cmdUntrapped_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdUntrapped.Click

 

Dim i As Short = 1234

Dim j As Short = 0

Dim k As Short = -1

k = CShort(i / j)

 

MessageBox.Show("Your reults are: " & k.ToString(), Me.Text, MessageBoxButtons.OK, MessageBoxIcon.Information)

End Sub

 

At this point you should be able to figure out what to do. You could log the error, show a messagebox, send an e-mail. The real key is to evaluate the exception you received using code like below. Note you should be careful. If you have an untrapped exception here, you will see the JIT debugging dialog, NOT the Windows Forms handler.

Uncomment the line below to see. Throw New ArgumentException("Oopss! I did it again!")

 

 

Friend Sub OnThreadException(ByVal sender As Object, ByVal t As System.Threading.ThreadExceptionEventArgs)

Dim exp As Exception = t.Exception

If TypeOf exp Is CustomerException Then

'Check for any CustomerExceptions

ElseIf TypeOf exp Is ApplicationException Then

'Check for any possible application exception

ElseIf TypeOf exp Is ArithmeticException Then

'You should see this dialog if you ran the

'code in cmdUntrapped_Click.

'Uncomment this line to verify.

MessageBox.Show(exp.Message, exp.Source, MessageBoxButtons.OK, MessageBoxIcon.Error)

ElseIf TypeOf exp Is SystemException Then

'Check for any possible system exception

Else

'Finally just plain old System.Exception

End If

Dim strMsg As String

strMsg = String.Format("We're sorry, an untrapped error occurred.{0}The error message was:{0}{1}", vbCrLf, exp.Message)

MessageBox.Show(strMsg, "Global Exception Trap", MessageBoxButtons.OK, MessageBoxIcon.Exclamation)

End Sub

 

Note: Source Code is given with that Article

   
Add Article Comment:
Name :
Email Address :
   
Comments :
 
   
<< Serializing & Deserializing Objects Using Standard and Binary Formatter in VB.Net

Disclaimer - Privacy
© 2002-2017 DevASP.net