Presentation is loading. Please wait.

Presentation is loading. Please wait.

Introduction to Error Handling

Similar presentations


Presentation on theme: "Introduction to Error Handling"— Presentation transcript:

1 Introduction to Error Handling
...or how to keep from shooting ourselves in the foot!

2 Using Un-Structured Error Handling
On Error Goto

3 Creating an Error Handler
Private Sub btnSave_Click... On Error GoTo MyErrHandler FileOpen (1, “FileName”, OpenMode.Output) ‘more code here Exit Sub MyErrHandler: MsgBox (“The following error occurred: “, err.Description) End Sub

4 Using Structured Error Handling
Try Catch Finally End Try

5 A Simple Error Trap File.Open(1, txtFileName.Text, FileMode.Open) Try
‘read the file Catch exp As Exception ' Will catch any error MessageBox.Show(exp.Message) End Try

6 Trapping Multiple Exceptions...
Try fs = File.Open(Me.txtFileName.Text, FileMode.Open) fs.Close() Catch exp As FileNotFoundException ' Will catch an error when the file requested does not exist. MessageBox.Show("The file you requested does not exist.", Me.Text, MessageBoxButtons.OK) Catch exp As DirectoryNotFoundException ' Will catch an error when the directory requested does not exist. MessageBox.Show("The directory you requested does not exist.", Me.Text, MessageBoxButtons.OK) Catch exp As IOException ' Will catch any generic IO exception. MessageBox.Show(exp.Message, Me.Text, MessageBoxButtons.OK, MessageBoxIcon.Stop) Catch exp As Exception ' Will catch any error that we're not explicitly trapping. End Try

7 Using “Finally” in the Try-Catch Scenario...
fs = File.Open(Me.txtFileName.Text, FileMode.Open) fs.Close() Catch exp As FileNotFoundException ' Will catch an error when the file requested does not exist. MessageBox.Show("The file you requested does not exist.", Me.Text, MessageBoxButtons.OK) Catch exp As Exception ' Will catch any error that we're not explicitly trapping. MessageBox.Show(exp.Message, Me.Text, MessageBoxButtons.OK, MessageBoxIcon.Stop) Finally ‘this always executes MessageBox.Show("File closed successfully in Finally block", Me.Text, MessageBoxButtons.OK) End Try

8 Final Decision... If YouAreTired = True Then The End = True Else
GrabACookie = True End If


Download ppt "Introduction to Error Handling"

Similar presentations


Ads by Google