Exceptions Handling

Exception Handling

In Visual Basic, errors (also calledexceptions) fall into one of three categories: syntax errors, run-time errors, and logic errors.

Syntax Errors

Syntax errorsare those that appear while you write your code. Visual Basic checks your code as you type and alerts you if you make a mistake, such as misspelling a word or using a language element improperly. Syntax errors are the most common type of errors. You can fix them easily in the coding environment as soon as they occur.

Run-Time Errors

Run-time errorsare those that appear only after you compile and run your code. These involve code that may appear to be correct in that it has no syntax errors, but that will not execute. For example, you might correctly write a line of code to open a file. But if the file is corrupted, the application cannot carry out the Openf unction, and it stops running. You can fix most run-time errors by rewriting the faulty code, and then recompiling and rerunning it.

Logic Errors

Logic errorsare those that appear once the application is in use. They most often take the form of unwanted or unexpected results in response to user actions. For example, a mistyped key or other outside influence might cause your application to stop working within expected parameters, or altogether. Logic errors are generally the hardest type to fix, since it is not always clear where they originate.


Visual Basic supports bothstructuredandunstructuredexception (error) handling. By placing specific code in your application, you can handle most of the errors users may encounter and enable the application to continue running. Structured and unstructured error handling allow you to plan for potential errors, preventing them from interfering with the intended purpose of the application.

Consider using exception handling in any method that uses operators that may generate an exception, or that calls into or accesses other procedures that may generate an exception.

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.

Structured Exception Handling

In structured exception handling, 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.

The Try...Catch...Finally statement is used specifically for structured exception handling.

Exception Class

To facilitate the use of structured exception handling, Visual Basic provides the ability to separate standard code from exception handling code. Exception handling code accesses an instance of the Exception class, which allows you to retrieve information about any exception you encounter.

Whenever an exception is thrown, the globalErrobject is set, and a new instance of an Exception class is created.

The properties of the Exception class aid in identifying the code location, type, and cause of exceptions. For example, the StackTrace property lists the called methods that led up to the exception, helping you find where the error occurs in the code. The Message property returns a text message describing the error; you can alter it to make a cryptic message easier to understand. If you do not supply an error message text string, the default is used.HelpLinkgets or sets a link to an associated help file.Sourcegets or sets a string containing the name of the object causing the error or the name of the assembly where the exception originated.

The Try...Catch...Finally Statement

The following code shows the structure of a Try…Catch…Finally statement:

Try

Place executable statements that may generate an exception in this block.

Catch [optional filters]

This code runs if the statements listed in the Try block fail and the filter on the Catch statement is true.

[Additional Catch blocks]

Finally

This code always runs immediately before the Try statement exits.

End Try

Ends a structured exception handler.

The Try block of a Try...Catch...Finally exception handler contains the section of code you want your error handler to monitor. 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 Catchblock. If no matching Catchstatement 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.

The code in theFinallysection always executes last, just before the error-handling block loses scope, regardless of whether the code in theCatchblocks has executed. Place cleanup code, such as that for closing files and releasing objects, in theFinallysection.

Unstructured Exception Handling

TheOnErrorstatement is used specifically for unstructured exception handling. In unstructured exception handling,On Erroris 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 anotherOn Errorstatement, that statement becomes valid and the first statement becomes invalid.

Inunstructuredexception handling, you place anOn Errorstatement at the beginning of a block of code, and it handles any errors occurring within that block. When an exception is raised in a procedure after theOn Errorstatement executes, the program branches to the line argument specified in theOn Errorstatement. The line argument, which is a line number or line label, indicates the exception handler location.

Sometimes a call is made from the original procedure to another procedure, and an exception occurs in the called procedure. In such cases, if the called procedure does not handle the exception, the exception propagates back to the calling procedure, and execution branches to the line argument.

On Error GoTo Line

TheOn Error GoTo Linestatement assumes that error-handling code starts at the line specified in the requiredlineargument. If a run-time error occurs, control branches to the line label or line number specified in the argument, activating the error handler.The specified line must be in the same procedure as theOn Error GoTo Linestatement; otherwise, Visual Basic generates a compiler error. The following example illustrates the use of an error handler with a line label:

Sub TestSub

On Error GoTo ErrorHandler

 Code that may or may not contain errors.

Exit Sub

ErrorHandler:

 Code that handles errors.

Resume

End Sub

The example contains an error handler named ErrorHandler. If any code in the TestSub subroutine generates an error, Visual Basic immediately executes the code that follows the ErrorHandler label. At the end of the error-handling block, theResumestatement passes control back to the line of code where the error first occurred. The rest of the subroutine then continues executing as if the error did not occur.

Note You must place anExitSubstatement immediately before the error-handling block. Otherwise, Visual Basic runs the error-handling code when it reaches the end of the subroutine, causing unwanted or unexpected results.

On Error Resume Next

TheOn Error Resume Nextstatement specifies that in the event of a run-time error, control passes to the statement immediately following the one in which the error occurred. At that point, execution continues.On Error Resume Nextenables you to put error-handling routines where errors will occur, rather than transferring control to another location in the procedure.

Note If your procedure calls another procedure, theOn Error Resume Next statement becomes inactive during the execution of the called procedure. Therefore, you should place anOn Error Resume Nextstatement in each called procedure that needs one. This is necessary because theResume Nextbehavior applies only to the procedure containing theOn Error Resume Nextstatement. If an unhandled error occurs in a called procedure, the exception propagates back to the calling procedure, and execution resumes on the statement following the call. In such cases, the error is not handled.

Resumealso can be used on its own, outside theOnErrorstatement. WhenResumeis used this way, Visual Basic returns control to the statement that caused the error. You generally useResumeafter an error handler corrects the error.

Visual Basic also provides theResumeNextstatement, which directs control to the line immediately following the line of code that caused the error. You might useResume Nextfor cases in which an error will not cause your application to stop working. You might also use it if an error will not change the expected results of your subroutine.

Another variation on theResumestatement isResumeLine, which is similar toOnErrorGoToLine.Resume Linepasses control to a line you specify in thelineargument. You can useResume Lineonly within an error handler.

Sub ErrorTest ()

Dim x As Integer, y As Integer, z As Integer

On Error GoTo DivideByZero

' The main part of the code, which might cause an error.

x = 2

y = 0

z = x \ y

On Error !GoTo 0

Console.WriteLine(x & "/" & y & " = " & z)

Exit Sub

DivideByZero:

Console.WriteLine("You have attempted to divide by zero!")

y = 2

Resume

End Sub

Example for Exception Handling

Creating the Application

The application in this walkthrough is a customer order form for a company that sells teddy bears. The user interface consists of the following controls: aTextBoxfor the customer's name, twoComboBoxcontrols to select the color and size of the bear, and anOrderbutton. When the user enters the requested information and clicks theOrderbutton, the application displays a summary of the order.

To create the application

  1. From theFilemenu, selectNew, and then selectProject. TheNew Projectdialog box appears.
  2. In theProject Typeswindow, selectVisual Basic Projectsif it is not already selected, and then chooseWindows Application from theTemplateswindow.
  3. In theNamebox, set the project name to TeddyBearProject. The project is added to Solution Explorer, and the Windows Forms Designer opens.
  4. Add the controls in the following table to the form, and set their properties as specified.
Control Properties Property Values
Label Name
Text
customerLabel
Bear Order Form
TextBox Name
Text
customerName
Customer Name
Label Name
Text
bearColorLabel
Available Colors
ComboBox Name
Items
Text
BearColor
Black, Brown, Spotted
Bear Color
Label Name
Text
bearSizeLabel
&Available Sizes
ComboBox Name
Items
Text
BearSize
Small, Normal, Large
Bear Size
Button Name
Text
Order
&Order

Adding Functionality

Now that the controls and their properties are added and set, you must place code behind them to make the application functional. The following code handles theClickevent for theOrderbutton and displays a message to the customer.

To add functionality to the form and its controls

  • Add the following code to theOrderbutton'sClickevent:
    Private Sub order_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Order.Click
    
    Dim bearOrder As String
    
    bearOrder = String.Format("You have ordered a !{0} !{1} bear.", 
    
    bearSize.SelectedItem, bearColor.SelectedItem)
    
    MessageBox.Show(bearOrder)
    
    End Sub
    

The application is now ready for you to add structured exception handling code.

Adding a Try...Catch Block

To ensure that the customer has specified a color for the bear, add aTry...Catchstatement. Keep the following considerations in mind:

  • ACatchclause with no identifier catches all exceptions.
  • ACatchclause with aWhenclause catches exceptions only when the expression evaluates toTrue; the type of the expression must be implicitly convertible toBoolean.

To add a simple Try...Catch block

  1. Add aTrystatement to theOrderbutton'sClickevent after the code line Dim bearOrder As String:

Try

  1. Add the following code to theOrderbutton'sClickevent after the section that tests the size and color values, that is, after String.Format(("You have ordered a !{0} !{1} bear.", BearSize.SelectedItem, BearColor.SelectedItem)". This code throws an exception if it encounters an invalid color value.
If ((BearColor.SelectedIndex < 0) or (BearColor.SelectedIndex > 2)) Then

Throw New System.Exception()

End If

 The Catch statement handles errors caused by a lack of bear color.

Catch ex As Exception When BearColor.SelectedIndex < 0

bearOrder = String.Format("You must select a bear color!")

Finally

Beep () ' Beep at the end.

End Try

To add an additional Catch clause

  1. Add a new item, "Purple", to the BearColorComboBoxcontrol.
  2. Add the following code after the code line bearOrder = String.Format("You must select a bear color!"):

Catch ex As Exception When BearColor.SelectedIndex = 3

bearOrder = String.Format("There are no purple bears!")

You can add as manyCatchclauses as necessary to your code.

Testing

You can now test the application to make sure it works correctly.

To build and run the application

  1. From theBuildmenu, selectBuild TeddyBearProject.
  2. Press F5 to run the application. The main form appears.

To test the application

  1. Enter a name in theCustomer nametext box, and then select a color and size for the bear from theAvailable ColorsandAvailable Sizestext boxes.
  2. Click theOrderbutton. If you specified eitherBlack,Brown, orSpottedas the color in the previous step, a message appears stating the size and color of the bear you ordered.

If you do not specify a color, a message appears prompting you to do so.

  1. ClickOKto cancel the message.
  2. In theAvailable Colorstext box, selectPurple, and then click theOrderbutton. A message appears stating that purple bears are not available.

13.1 Shadows & Exceptions

The keyword Shadows means that when a member of a derived class has the same name as a member of the same type in the base class, then the member in the derived class entirely replaces all variations of the method from the base class, leaving the derived class with only a single version of the method, that is, the one created in the derived class. To create a shadows member in vb.net – Shadows <function_type> < funs_name>

To create a shadows member in c#.net – new <function_type> < funs_name>

Example For Shadows in C#:-

**************To declare a Class***************

public class BaseClass_Shadows

{

public void sum(int a)

{

a = a * a;

MessageBox.Show("Square Value Is : "+a.ToString());

}

C# language uses many types of exceptions, which are defined in special classes.

All of them are inherited from base class named System.Exception. There are classes that process many kinds of exceptions: out of memory exception, stack overflow exception, null reference exception, index out of range exception, invalid cast exception, arithmetic exception etc. This c# document deals with DivideByZero c# exception and custom classes in c# exceptions.

C# has defined some keywords for processing exceptions. The most important are try,catchandfinally.

// try catch exception

int zero = 0;

try

{

	int div = 100/zero;

}

catch(DivideByZeroException)

{

	Console.WriteLine("Division by zero exception passed");

}

}

public class DerivedClass_Shadows : BaseClass_Shadows

{

	public new void sum(int a)

	{

		a = a * a* a;

		MessageBox.Show("Cube Value Is : "+a.ToString());

	}

}

*************To declare an Object**************

private void button16_Click(object sender, EventArgs e)

{

	BaseClass_Shadows ob = new BaseClass_Shadows();

	ob.sum(50);

	DerivedClass_Shadows obj = new DerivedClass_Shadows();

	obj.sum(20);

}

This code in runtime throws a DivideByZeroException and writes some message through the console. But if you want to release some resources that were created you must use try ? Finally construction. Finally will be called even if there were no exceptions raised.

//Sample code for C# Exception tutorial using try, finally

Bitmap bit = null;

// try finally exception

try

{

bit = new Bitmap(100,100);

}

finally

{

bit.Dispose();

Console.WriteLine("bitmap is disposed");

}
Last modified: Sunday, 30 September 2012, 3:27 PM