Recipe 15.4. Displaying Exception Information


Problem

An error has occurred, and you want to inform the user in a friendly manner.

Solution

The captured exception object includes all the details concerning the error, with some parts ready for user-friendly presentation. The simplest presentation option uses the exception's ToString() method to generate information about the error.

The following code generates the error message in Figure 15-1 when run within Visual Studio:

 Try    Throw New System.Exception( ) Catch ex As System.Exception    MsgBox(ex.ToString( )) End Try 

Figure 15-1. A basic error message


Discussion

If you encounter an exception in a block of code where you know errors are likely, you can sometimes compensate for the error through alternate logic without ever informing the user of the problem. In those cases where you cannot continue normally because of the error, your program can inform the user of the situation.

Beyond the basic ToString() output, you can handcraft the details of the exception into a form that better communicates the problem to the user. The System.Exception object includes the following useful properties:


Data

Some errors use the collection exposed by this property to store additional details related to the error. The type of data stored depends on the code that generated the error. It is most often used in custom exceptions.


InnerException

If this exception is a byproduct of another, earlier exception, this property exposes that previous exception.


Message

This property provides a short yet friendly description of the exception.


Source

This property specifies the name of the application, class, or process ID that generated the error.


StackTrace

This text property provides a semihuman-readable listing of the stack tracethe set of called methods that led up to the method generating the error. This stack trace may include internal procedures from the .NET Framework, and its overall length may shock the user.


TargetSite

This property exposes a MethodBase object that fully describes the procedure in which the exception occurred. The properties of this object may or may not be useful in every case, especially when an application has been obfuscated.

Other exception objects further derived from System.Exception may include additional properties with more detailed information. By concatenating the various properties of the captured exception object, you should be able to effectively communicate the problem to the user or store the details in an error log for later analysis.




Visual Basic 2005 Cookbook(c) Solutions for VB 2005 Programmers
Visual Basic 2005 Cookbook: Solutions for VB 2005 Programmers (Cookbooks (OReilly))
ISBN: 0596101775
EAN: 2147483647
Year: 2006
Pages: 400

Similar book on Amazon

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