.NET Exceptions
In this tutorial you will learn about Exceptions, Common Exceptions, Handling Exceptions – Try Block, Catch Block, Throw Statement, Finally Block, Salient points about error handling Custom Exceptions – Managing Unhandled Exception
Exceptions
Abnormal conditions can become obstacles in the execution of very good programs. These conditions may force the program to breakdown, or halt or just go into a limbo. The Network connection may snap or a printer may run out of paper. No programmer can foresee these problems, yet he must give the user an option to gracefully save the work done up to the point and exit the program. The Exception Management Application Block provides a simple yet extensible framework for handling exceptions in VB.NET.
What is an Exception?
Programs are designed to execute normally in predefined conditions. However, the program may occasionally be confronted with an abnormal situation which it is not built to handle. Such a situation will result in an “exception” to the norm. Programs will have to be told what it has to do when it encounters such abnormal conditions. The process of anticipating and providing for handling such extraordinary situations is known as exception handling. In .Net Framework 2005 we have a facility to break, correct the code and continue in case of exception. This facility was withdrawn in the earlier releases of .Net Framework.
An exception may occur due to a logical or a syntax error. Where syntax errors may be caught by the complier, logical errors are likely to be missed Therefore, you may have a program that may be trying to delete a file that does not exist or it may be trying to divide by zero or it may just be a null pointer error or a System IO exception. The program must be told what to do and how to do it. Some of these code level bugs come to light only at the time of execution or under extreme conditions. Most programmers as a matter of caution create exceptions and raise them on some predefined conditions to monitor the working of the program. They ensure that they provide for exception handling for the most commonly encountered problems and situations. Microsoft .NET framework 2005 has made this task of the programmer easier by building into the application the Exception Assistant.
An example of an exception handler code is illustrated below for your understanding:
In the above example a class has been instantiated and the SecondMethod is called. In the above code two variables a and b are passed on to the SecondMethod and a process is initiated in the SUB. Once this process is complete the SUB FirstMethod is called. The expected condition here is that the value of ‘n’ should not be zero. If at this point the value of “n” is set to zero the program will breakdown or terminate.
The Exception Assistant helps the programmer troubleshoot exceptions and also helps him understand more about the exceptions.
Some of the most common exceptions are listed below:
-
Code Access Security Exceptions
-
MicroSoft.Tools.CannotRemoveControlException
-
System.AccessViolationException
-
System.ArrayTypeMismatchExceptionSystem.Data.OleDb.OleDbException
-
System.Data.ConstraintException
-
System.Data.InvalidExpressionExcepton
-
System.Data.NoNull.AllowedException
-
System.Data.OdbcExcepton
-
System.Data.OracleClient.OracleException
-
System.DivideByZeroException
-
System.DuplicateWaitObjectException
-
System.IO.DirectroyNotFoundException
-
System.IO.EndOfStreamException
-
System.IO.FileNotFoundException
-
System.IO.IOException
-
System.IO.PathTooLongException
-
System.IO.InternalBufferOverflowException
-
System.NotSupportedException
-
NullReferenceException
-
System.ObjectDisposedException
-
System.OperationCalnceledException
-
System.OutOfMemoryException
-
System.OverflowException
-
System.Security.SecurityException
-
System.StackOverFlowException
-
System.UnauthorizedException
Handling Exceptions
Visual Basic supports both Structured and unstructured exception handling. If an exception occurs in a method that is not equipped to handle it, the exception is propagated back to the calling method, or the previous method. If the previous method also has no exception handler, the exception is propagated back to that method’s caller, and so on. The search for a handler continues up the call stack, which is the series of procedures called within the application. If it fails to find a handler for the exception, an error message is displayed and the application is terminated.
The On Error statement is used specifically for unstructured exception handling. In unstructured exception handling, On Error is placed at the beginning of a block of code. It then has "scope" over that block; it handles any errors occurring within the block. If the program encounters another On Error statement, that statement becomes valid and the first statement becomes invalid.
In the Structured Exception Handling, the blocks of code are encapsulated with each block having one or more associated handlers. Each handler specifies some form of filter condition on the type of exception it handles. When an exception is raised by code in a protected block, the set of corresponding handlers is searched in order, and the first one with a matching filter condition is executed. A single method can have multiple structured exception handling blocks, and the blocks can also be nested within each other.
Using the Try…Catch…Finally statement, you can protect blocks of code that have the potential to raise errors. You can nest exception handlers, and the variables declared in each block will have local scope.
.
.
The Try Block
The try block can be defined as code that can possibly raise exceptions—for instance mathematical calculations, Database Connection and queries, Writing to a log file, or reading from a file. The Try block, the Catch block and the Finally… function together to handle the exception.
The Catch Block
A single Try block can have more than one catch block. If an error occurs during execution of any of the code in this section, Visual Basic examines each Catch statement within the Try…Catch…Finally until it finds one whose condition matches that error. If one is found, control transfers to the first line of code in the Catch block. If no matching Catch statement is found, the search proceeds to the Catch statements of the outer Try…Catch…Finally block that contains the block in which the exception occurred. This process continues through the entire stack until a matching Catch block is found in the current procedure. If none is found, an error is produced. General exception handler to catch any other exceptions can also be added.
The Throw Statement
You can also explicitly use a throw statement to throw or re-throw an exception. Let us see an example for this now. Any exception that prevents further flow of information is automatically thrown which are handled in the try catch finally blocks. However user generated exceptions are used to be thrown in this fashion. You need do explicitly use throw statement to throw these exceptions that will be handled by the try catch finally blocks. For this purpose you need to create a new object based on the ApplicationException Object.
The Finally Block
The code in the Finally block is always executed at the end, just before the error handling block loses scope, irrespective of whether the code in Catch blocks has executed or not. This block is normally used to clean up the code.
Salient points about error handling:
-
Local variables from a Try block are not available in a Catch block because they are separate blocks. If you want to use a variable in more than one block, declare the variable outside the Try…Catch…Finally structure.
-
If errors occur that the programmer has not handled, Visual Studio for Applications simply provides its normal error message to a user, as if there was no error handling.
-
The Try block contains code where an error can occur, while the Catch block contains code to handle any error that does occur. If an error occurs in the Try block, program control is passed to the appropriate Catch statement for disposition. The exception argument is an instance of the Exception class or an instance of a class that derives from the Exception class corresponding to the error that occurred in the Try block. The Exception class instance contains information about the error including, among other things, its number and message.
-
In partial trust situations, such as an application hosted on a network share, Try…Catch…Finally will not catch security exceptions that occur before the method containing the call is invoked.
Custom Exceptions
The exceptions that are raised can be classified in to two categories.
Managing Unhandled Exceptions
Click here for Sample Code
Unhandled exceptions events can be moved into an assembly wide class so that it can be accessed by other forms. The unhandled exception generates an AbortIgnoreRetry dialog box giving the full description of the error.