error trapping exception catching 1. syntax & compile-time vb – editor/compiler logic and...

Post on 18-Jan-2018

243 Views

Category:

Documents

0 Downloads

Preview:

Click to see full reader

DESCRIPTION

When performing data validation, some errors are easy to detect and respond to. Remember our initial interest program: 3home

TRANSCRIPT

Error Trapping

Exception Catching1

• Syntax & Compile-time VB – Editor/Compiler

• Logic and Design You

• Runtime You

Types of Errors:

2

When your program bombs!

When performing data validation, some errors are easy to detect and respond to. Remember our initial interest program:

3home

100

3

5

4

IsNumericPrivate Sub (…) Handles cmdCalculate.Click

lblResult.Text = txtPrin.Text * txtRate.Text * txtTime.Text

End Sub

Private Sub (…) Handles cmdCalculate.Click

If (Not IsNumeric(txtTime.Text)) Then msgbox(…)

txtTime.SelectAll()txtTime.Text = “”

Exit Sub End If

lblResult.Text = txtPrin.Text * txtRate.Text * txtTime.Text

End Sub

Of course, we would have to dothis for each of the TextBoxes.

Note: this code also handles anempty TextBox.

Structured Exception Handling

5

Common Exception Classes

Exception Caused By

FormatException Failure of a numeric conversion, such as Integer or Parse.Usually blank or nonnumeric fields.

InvalidCastException Failure of a conversion operation. May be caused by loss of significant digits or an illegal conversion.

ArithmeticException A calculation error, such as division by zero.

OverflowException Overflow of a variableDim x As Integerx = 1000000000

IndexOutOfRangeException An array’s index is out of range.Dim x(5) As Integerx(9) = 25

Exception Generic - any exception

Structured Exception Handling

6

Try statements that may cause an errorCatch [name As Exception] action statements when an exception occurs[Finally statements that always execute before exiting try block]End Try

Structured Exception Handling

7

Private Sub (…) Handles cmdCalculate.Click

Try lblResult.Text = txtPrin.Text * txtRate.Text * txtTime.Text Catch ex As Exception msgbox(ex.Message & "|" & ex.GetType.ToString) Exit Sub End Try

End Sub

This is not as good as the previous example, but itdoes show that all of theTextBox errors are caught.

By naming exceptions, you can access their propertiesand methods.

Catches any exception

We are going to focus on using exception handlingwhen workingon files.

8

Structured Exception Handling

9

File Related Exception Classes

Exception Caused By

IO.DirectroyNotFoundException A file within a missing folder is accessed.

IO.FileNotFoundException A missing file is accessed.

IO.IOException Any file-handling exception including the two mentioned above.For example, an attempt is made to delete or move an open file.

Dim inFile As StreamReader

Try inFile = File.OpenText(“D:\Dimensions\measures.txt”)...

Catch ex As IODirectoryNotFoundException msgbox(“The requested folder is not on the CD.”)Catch ex As FileNotFoundException msgbox(“The file is not in the specified folder.”)Catch ex As IOException msgbox(“Check to see if there is a CD in drive D:.”)Finally inFile.close()End Try...

10

Assume D: is a CD drive

Exceptions are caughtfrom the most specificto the most general

Private Sub cmdRead_Click(…) Handles cmdRead.Click Dim inFile As StreamReader inFile = File.OpenText("GBA.txt") lblGB.Text = inFile.ReadToEnd inFile.Close() End Sub

11

Remember, the filehas to be in the samedirectory as the .exe file

Gettysburg Address Revisited

Private Sub cmdRead_Click(…) Handles cmdRead.Click Dim inFile As StreamReader inFile = File.OpenText("GBA.txt") lblGB.Text = inFile.ReadToEnd inFile.Close() End Sub

12

Gettysburg Address Revised

Try Catch ex As FileNotFoundException msgbox(“The file is not in the specified folder.”) Exit Sub End Try

Let’s examine a far more elegant wayto open files using built-in dialog boxes

OpenFileDialog Box

13

14

Gettysburg Address Re-revised

We will use a menu item to display a filedialog box, from which we will select a file

Private Sub FileOpenToolStripMenuItem_Click(…) … Dim inFile As StreamReader

.ShowDialog() inFile = File.OpenText(MyOpenFileDialog.FileName) txtGB.Text = inFile.ReadToEnd inFile.Close()End Sub

15

An OpenFileDialog property

To learn more aboutOpenFileDialog use Help

An OpenFileDialog method which also returnsa value indicating which button was pressed

This code creates and displays an OpenFileDialog box withMOST error trapping/exception catching already done!

OpenFileDialog Box

MyOpenFileDialog

Private Sub FileOpenToolStripMenuItem_Click(…)… Dim inFile As StreamReader

MyOpenFileDialog.ShowDialog() inFile = File.OpenText(MyOpenFileDialog.FileName) txtGB.Text = inFile.ReadToEnd inFile.Close()End Sub

16

There is at least twoerrors that the OpenFileDialog

box does not handle!

OpenFileDialog Box Improvements

MyOpenFileDialog.InitialDirectory = "C:\Users\Anthony

Nowakowski\Documents\Visual Studio 2010\Projects“

MyOpenFileDialog.Filter = "txt files (*.txt)|*.txt|csv

files (*.csv)|*.csv"

Private Sub FileOpenToolStripMenuItem_Click(…)… Dim inFile As StreamReader

inFile = File.OpenText(MyOpenFileDialog.FileName) txtGB.Text = inFile.ReadToEnd inFile.Close()

End Sub

17

OpenFileDialog Box Improvements

MyOpenFileDialog.InitialDirectory = "C:\Users\Anthony

Nowakowski\Documents\Visual Studio 2010\Projects“

MyOpenFileDialog.Filter = "txt files (*.txt)|*.txt|csv

files (*.cs)|*.csv"If(MyOpenFileDialog.ShowDialog()= DialogResult.Cancel) Then Exit SubElse

End If Note: this code handles boththe Cancel button and the Red X

You could have also testedDialogResult.OK

18

Other Dialog Boxes

• SaveFileDialog - MySaveFileDialog.ShowDialog() Also found in the Toolbox under Dialogs

• ColorDialog - MyColorDialog.ShowDialog() Also found in the Toolbox under Dialogs

• PrintDialog - MyPrintDialog.ShowDialog() Found in the Toolbox under Printing

In addition to the OpenFileDialog box,there are several including:

You will be implementing SaveFileDialog

in your next assignment

Read the Description

Of Assigment-5

19

top related