Exceptions in visual studio .net

After you have completed testing and debugging your application, run-time errors might still be inevitable. For example, an application that saves data to a floppy disk will encounter an error if it attempts to save to a disk that is not ready. Even though the application code might execute as designed, an error will still result.

Visual Basic .NET and Visual C# provide structured exception handling as a means of writing code that recovers gracefully from errors and allows program execution to continue. You can also create and throw exceptions from your components that communicate to the main program that an error has occurred.

When an application encounters a run-time error, it raises an exception. Exceptions are instances of specialized classes that all derive from the base class System.Exception. Exceptions include features that facilitate diagnosis and management of the error, such as:

The Message property, which can contain a human-readable description of the error as well as any other relevant information about the error.
The StackTrace property, which contains a stack trace to allow tracing and pinpointing of where the error occurred in the code.

When a run-time error is encountered, an instance of the exception corresponding to the error is created and passed from the method that generated the error up the call stack to the method that called it. If an exception handling structure is encountered in that method, it is handled there.

If no exception handling structure is found, the exception is passed further up the call stack to the next method, and so on. If no exception handling structure is found anywhere in the call stack, the default exception handler is engaged. This causes a message box to display the type of exception and any additional information provided by it, and then the application is terminated without any opportunity to save work or attempt to recover from the error.

With structured exception handling, you can provide a means for your application to recover from unexpected errors or at least have the chance to save data before closing.

Creating an Exception Handler

Exception handlers are implemented for specific methods. Thus, each method you create can have its own exception handler, specifically tailored to the method and exceptions it is likely to throw. Methods that are likely to throw exceptions, such as methods that involve file access, should implement exception handling. Exception handlers use a Try...Catch...Finally syntax. Three general steps are involved in creating an exception handler:

  1. Wrap the code the handler will be associated with in a Try (try) block.
  2. Add one or more Catch (catch) blocks to handle the possible exceptions.
  3. Add any code that must always be executed to a Finally (finally) block. Such code will execute regardless of whether or not an exception is thrown.

The first step in creating an exception handler is to wrap the code in a Try (try) block. The Try (try) block forms the exception handler; if an exception is thrown by any statement in the code or any unhandled exception is received through call stack bubbling, the method will attempt to handle it within this exception handler. If the exception cannot be handled, it will be bubbled further up the call stack.

In Visual Basic .NET, you can exit a Try block by using the Exit Try statement.

A Try (try) block can be followed by one or more Catch (catch) blocks. A Catch (catch) block contains code to be executed when an exception is handled. Catch (catch) blocks can be generic, catching all possible exceptions, or specific, catching exceptions of a given class. The following example demonstrates a completely general Catch (catch) block that will catch all exceptions thrown within a given Try (try) block.

You can also obtain a reference to the exception that was thrown in the Catch (catch) statement. This can be useful because it allows you to access information contained within the exception in your error handling routine. It also allows you to screen errors by type and create multiple Catch (catch) blocks to handle specific errors. The following example demonstrates how to catch a specific exception.

Finally (finally) blocks contain code that must be executed regardless of whether an exception is thrown. This could include code to save data or release resources, or other code that is crucial to the application. The following code example demonstrates a Try...Catch...Finally (try...catch...finally) block .

If an error is encountered within a Try (try) block, execution is immediately transferred to the Catch (catch) blocks. The Catch (catch) blocks are then examined for one that can catch the exception that is thrown.

In the preceding example, there are two Catch (catch) blocks—one that specifically catches an ArgumentNullException and one that catches any other exceptions. Only one Catch (catch) block will be executed per error. After the code in the Catch (catch) block has executed, the code in the Finally (finally) block is executed. Normal application execution then resumes at the next line after the line that called the error containing routine.

At times, you might not want to handle exceptions in your local routine but instead bubble them up to the method that called your routine. Even so, you might have code that needs to run even in the event of an exception. In this case, you can omit the Catch (catch) block and use a Try...Finally (try...finally) structure.

To create an exception handler

Wrap the code for which you want to handle errors within a Try (try) block.
If you want to handle exceptions locally, create one or more Catch (catch) blocks that contain the appropriate code to handle the exception.

If you have any code that must be executed, even in the event of an exception, enclose it within the Finally (finally) block.

Throwing Exceptions

There might also be cases when you want to throw exceptions. Generally speaking, these cases are divided into two situations:

You cannot completely handle a run-time error but want to partially handle it, and then bubble the exception up the call stack.

An unacceptable condition has occurred in a component that cannot be handled locally and needs to be communicated to its parent. This might involve throwing either a standard .NET exception, or a custom exception specific to your component.

Rethrowing Exceptions

At times, your exception handling structure might not be able to fully handle your exception. For example, you might have a method that is performing an extensive series of complex calculations when suddenly a NullReferenceException is thrown. The method might or might not be able to handle the exception.

Your code should test conditions and determine whether or not it can handle the exception. If the exception cannot be handled in the context of the Catch (catch) block, your code should rethrow the exception by using the Throw (throw) keyword.

Alternatively, you might want to provide additional information to the next application level. Instead of rethrowing the same exception, you can wrap that exception in a new exception. The InnerException property is set in the constructor of a new exception and can hold a reference to an existing exception.

Thus, you can supplement the information contained within the system exception by setting the relevant properties of a new exception and wrapping the original exception in the InnerException property. The following example demonstrates how to create and throw a new exception that provides an informative string message and wraps the original exception.

To rethrow an exception

Choose the appropriate option from the following:

Use the Throw (throw) keyword to throw the exception that was received by the Catch (catch) block.

Wrap the exception in a new exception that provides additional information and use the Throw (throw) keyword to throw it.

Custom Exceptions

A second scenario in which you might throw a new exception is in component development. If a condition occurs in your component that cannot be resolved, it is proper to throw an exception to the client application. Exceptions of this type will almost always be custom exceptions because the common language run time will throw an exception if any of the standard exception conditions occur.

You can create custom exceptions by inheriting from the System.ApplicationException class. The ApplicationException class encapsulates all of the functionality that an exception requires including the Message, StackTrace, and InnerException properties, and can serve as a base for custom functionality that can be tailored to your component.

To throw a custom exception

Define the custom exception class. It should inherit System.ApplicationException and expose any properties that will provide additional information to the clients that will handle the exception. The values of these properties should be assignable through the class's constructor.

When appropriate, use the Throw keyword to throw a new instance of the exception, setting any appropriate parameters in the constructor.

related post











No comments:

Post a Comment