Sams Teach Yourself Visual Studio .NET 2003 in 21 Days

Sams Teach Yourself .Net in 21 Days

By Jason Beres

Understanding Exceptions in .NET

When an error occurs in a Visual Basic 6.0 application, the Err object fills with information about the last error that occurred. Your application is then thrown that error information, and the error is handled by the On Error code you wrote. In Visual Basic .NET, the Err object still exists, but for backward compatibility only. In C#, the Err object doesn't exist. To make your code compliant with the Common Language Specification (CLS), you must use the exception object from the System.Exception class in the Framework Class Library (FCL).

The Exception object contains the information you need about the last error that occurred in your application. When an error occurs, an Exception object is created. So, when a block of code causes an error, an exception is thrown and the first block of code in the stack that has an exception handler takes care of that exception. If there's no exception-handling code, a runtime error occurs, and your application terminates. Table 7.1 lists the properties of the Exception object.

Table 7.1. Properties and Descriptions of the Exception Object

Property Name

Property Description

HelpLink

Gets or sets the help file associated with the application

InnerException

Gets a reference to the inner exception

Message

Gets a string representing the error message associated with the exception

Source

Gets or sets the name of the application object that caused the exception

StackTrace

Gets the stack trace identifying the location in the code where the exception occurred

TargetSite

Gets the method name where the exception occurred

Using the properties of the Exception object, you can determine what to do about the exception that occurred. This might be notifying the user with a MessageBox prompt or handling the error and continuing execution in your code.

Now that you understand what an exception is, you need to learn how to handle them in code. In .NET, you use structured exception handling (SEH) to help you handle errors in code.

Share ThisShare This

Informit Network