6.2 Unhandled Exception Handler

only for RuBoard

The stack trace that results from an unhandled exception is a default handler. It's a nice feature, but it is not very robust. It might work well for grandma's little recipe program, but in a bulletproof, industrial-strength application, it just won't do. Errors need to be logged to the event log or a database, emails need to be sent to technical support, and programmers need to be paged in the wee hours o' the morning. More than likely, you will probably need to use the stack trace information in conjunction with other forms of error reporting.

Fortunately, the .NET Framework is very giving in this area. You are free to substitute your own handler for unhandled exceptions, as demonstrated in Example 6-4.

Note the call to the AppDomain.CurrentDomain method in the Main procedure in Example 6-4. Calling AppDomain.CurrentDomain returns an object that represents the current application domain. Recall from Section 2.4 of Chapter 2 that an application domain is the execution environment for a .NET assembly. The instance of AppDomain that is returned as a result of this call provides a number of interesting properties and methods . Here are a few:

BaseDirectory property

Returns the path of the application. It is similar to App.Path in earlier versions of VB.

FriendlyName property

Returns the name of the executable. It is similar to App.EXEName in earlier versions of VB.

ExecuteAssembly method

Executes the specified assembly. It is similar to Shell in earlier versions of VB.

AppDomain also provides an event that is called when an unhandled exception occurs. You only need to provide an event handler for it by using AddHandler . Then you can write the error to the event log, fire off an email, or do whatever needs to be done, as Example 6-4 illustrates.

Example 6-4. Unhandled exception handler
 'vbc /t:exe /r:system.dll /r:system.web.dll     Imports System Imports System.Diagnostics Imports System.Web.Mail     Friend Class ReallyBadClass   Public Sub ReallyBadMethod( )       'Throw an exception       Throw New ArgumentException("Simulated Error")   End Sub End Class     Friend Class BadClass   Public Sub BadMethod( )       Dim rb As New ReallyBadClass( )       rb.ReallyBadMethod( )   End Sub End Class     Public Class App       'Unhandled exception handler   Public Shared Sub MyExceptionHandler( _               ByVal sender As Object, _               ByVal e As UnhandledExceptionEventArgs)           Dim break As New String("-"c, 70)       Console.WriteLine( )       Console.WriteLine("Unhandled Exception")       Console.WriteLine(break)       Console.WriteLine("{0}", e.ExceptionObject)       Console.WriteLine(break)       Console.WriteLine("Writing to event log...")       Console.WriteLine("Sending email to tech support...")           'Write to event log       Dim myLog As EventLog = New EventLog( )       myLog.Source = "Application Log"       myLog.WriteEntry("My Bad Application", _           e.ExceptionObject.ToString( ), EventLogEntryType.Error)           'Can sending an email be easier?       Dim mailMsg As New MailMessage( )       mailMsg.To = "techsupport@somedomainhere.com"       mailMsg.Subject = "My Bad Application - Exception"       mailMsg.Body = e.ExceptionObject.ToString( )           'Your outgoing SMTP server goes here       Try         SmtpMail.SmtpServer = "mail.someserver.com"         SmtpMail.Send(mailMsg)       Catch x As Exception         Debug.Write("Use a real SMTP server")       End Try              'Keep the example code up and running       Console.WriteLine( )       Console.WriteLine("Press ENTER to continue...")       Console.ReadLine( )       End Sub       Public Shared Sub Main( )     'This replaces the default unhandled exception     'handler with ours     Dim domain As AppDomain = AppDomain.CurrentDomain( )     AddHandler domain.UnhandledException, _         AddressOf MyExceptionHandler         'Cause exception on purpose     Dim b As New BadClass( )     b.BadMethod( )     Console.ReadLine( )   End Sub     End Class 

The output from this program contains the call stack that the default handler provides via e.ExceptionObject :

 Unhandled Exception ---------------------------------------------------------------------- System.ArgumentException: Simulated Error    at ConsoleApplication3.ReallyBadClass.ReallyBadMethod( )         in C:bad.vb:line 12    at ConsoleApplication3.BadClass.BadMethod( )         in C:\bad.vb:line 19    at ConsoleApplication3.App.Main( )         in C:\bad.vb:line 67 ---------------------------------------------------------------------- Writing to event log... Sending email to tech support... 

It also shows how code could be added to handle exceptions in a variety of different ways. You can easily add an entry to the event log, and sending email has never been easier. Just a few lines of code are all it takes.

only for RuBoard


Object-Oriented Programming with Visual Basic. Net
Object-Oriented Programming with Visual Basic .NET
ISBN: 0596001460
EAN: 2147483647
Year: 2001
Pages: 112
Authors: J.P. Hamilton

Similar book on Amazon

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net