Visual Basic:TRY \ CATCH异常处理问题

时间:2018-10-18 20:04:16

标签: vb.net exception-handling try-catch

我正在处理一个员工数据库,并且TRY \ CATCH遇到与异常处理有关的记录保存问题。我遇到的问题是它将运行TRY并忽略CATCH,从而允许传递无效数据并将其保存到文件。我对Visual Basic非常陌生,不确定为什么它不起作用。这是我的表单代码:

Option Strict Off
Imports System.IO

Public Class frmEmployeeData
'Variable Declarations
Dim BlnisChanged As Boolean = False
Dim empFirstName As String
Dim empMiddleName As String
Dim empLastName As String
Dim empNumber As Integer
Dim empDepartment As String
Dim empTelephone As String
Dim empExtension As Integer
Dim empEmailAddress As String
Dim empSelection As String
Dim fileName As String
Dim intTryParse As Integer = 0



Private Sub frmEmployeeData_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    'Adds the department options to the combo box dropdown list
    ComboBoxEmpDepartment.Items.Add("Accounting")
    ComboBoxEmpDepartment.Items.Add("Administration")
    ComboBoxEmpDepartment.Items.Add("Marketing")
    ComboBoxEmpDepartment.Items.Add("MIS")
    ComboBoxEmpDepartment.Items.Add("Sales")
End Sub

Sub ClearItems()
    'Clears text boxes
    txtFirstName.Clear()
    txtMiddleName.Clear()
    txtLastName.Clear()
    txtEmployeeNumber.Clear()
    ComboBoxEmpDepartment.ResetText()
    txtTelephone.Clear()
    txtExtension.Clear()
    txtEmailAddress.Clear()
End Sub

Sub SaveItems()
    Dim savedEmployeeFile As StreamWriter

    Try
        'Creates the employee file
        savedEmployeeFile = File.CreateText(fileName)

        'writes information entered by user into file
        savedEmployeeFile.WriteLine(txtFirstName.Text)
        savedEmployeeFile.WriteLine(txtMiddleName.Text)
        savedEmployeeFile.WriteLine(txtLastName.Text)
        savedEmployeeFile.WriteLine(txtEmployeeNumber.Text)
        savedEmployeeFile.WriteLine(ComboBoxEmpDepartment.Text)
        savedEmployeeFile.WriteLine(txtTelephone.Text)
        savedEmployeeFile.WriteLine(txtExtension.Text)
        savedEmployeeFile.WriteLine(txtEmailAddress.Text)

        'Closes the file
        savedEmployeeFile.Close()

        BlnisChanged = False

        'Clears the text boxes
        ClearItems()

    Catch ex As Exception
        'Throws error if file could Not be created
        MessageBox.Show("Unable To Create File. Please Try Again", "Error In Saving")

    End Try
End Sub
Sub AppendToFile()
    Dim savedEmployeeFile As StreamWriter

    Try
        'append to file
        savedEmployeeFile = File.AppendText(fileName)

        'writes information entered by user into file
        savedEmployeeFile.WriteLine(txtFirstName.Text)
        savedEmployeeFile.WriteLine(txtMiddleName.Text)
        savedEmployeeFile.WriteLine(txtLastName.Text)
        savedEmployeeFile.WriteLine(txtEmployeeNumber.Text)
        savedEmployeeFile.WriteLine(ComboBoxEmpDepartment.Text)
        savedEmployeeFile.WriteLine(txtTelephone.Text)
        savedEmployeeFile.WriteLine(txtExtension.Text)
        savedEmployeeFile.WriteLine(txtEmailAddress.Text)

        MessageBox.Show("Employee saved successfully.", "Success")

        'Closes the file
        savedEmployeeFile.Close()


        BlnisChanged = False

        'Clears the text boxes
        ClearItems()
    Catch ex As Exception
        MessageBox.Show("No file exists. Please select 'Save As' Option.", "Error In Saving")
    End Try
End Sub

Private Sub btnSaveRecord_Click(sender As Object, e As EventArgs) Handles btnSaveRecord.Click
    Dim savedEmployeeFile As StreamWriter

    'EXCEPTION HANDLING
    'verifies first name field content
    If txtFirstName.Text = "" Then
        MessageBox.Show("First name cannot be blank", "Invalid Entry")
    End If
    'verifies middle name field content
    If txtMiddleName.Text = "" Then
        MessageBox.Show("Middle name cannot be blank", "Invalid Entry")
    End If
    'verifies last name field content
    If txtLastName.Text = "" Then
        MessageBox.Show("Last name cannot be blank", "Invalid Entry")
    End If
    'verifies employee number field content
    If txtEmployeeNumber.Text = "" Then
        MessageBox.Show("Employee number cannot be blank", "Invalid Entry")
    ElseIf Not (Integer.TryParse(txtEmployeeNumber.Text, intTryParse)) Then
        MessageBox.Show("Employee number must be numeric", "Invalid Entry")
    ElseIf CStr(txtEmployeeNumber.Text) < 0 Then
        MessageBox.Show("Employee number must be positive", "Invalid Entry")
    End If
    'verifies department field content
    If ComboBoxEmpDepartment.Text = "" Then
        MessageBox.Show("Employee department cannot be blank", "Invalid Entry")
    End If
    'verifies telephone number field content
    If txtTelephone.Text = "" Then
        MessageBox.Show("Telephone number cannot be blank", "Invalid Entry")
    ElseIf Not (Integer.TryParse(txtEmployeeNumber.Text, intTryParse)) Then
        MessageBox.Show("Telephone number must be numeric", "Invalid Entry")
    End If
    'verifies extension field content
    If txtExtension.Text = "" Then
        MessageBox.Show("Extension cannot be blank", "Invalid Entry")
    ElseIf Not (Integer.TryParse(txtExtension.Text, intTryParse)) Then
        MessageBox.Show("Extension must be numeric", "Invalid Entry")
    ElseIf CInt(txtExtension.Text) < 0 Then
        MessageBox.Show("Extension must be positive", "Invalid Entry")
    End If
    'verifies email address field content
    If txtEmailAddress.Text = "" Then
        MessageBox.Show("Email Address cannot be blank", "Invalid Entry")
    End If


    'If no filename exists, will prompt save dialog box and prompt user to save as
    If fileName = String.Empty Then
        If sfdSave.ShowDialog = System.Windows.Forms.DialogResult.OK Then
            fileName = sfdSave.FileName
            SaveItems()
        End If

        'If filename exists, append item to file
    Else
        AppendToFile()
    End If
End Sub

Private Sub btnClear_Click(sender As Object, e As EventArgs) Handles btnClear.Click
    'Clears all content currently within text boxes
    txtFirstName.Clear()
    txtMiddleName.Clear()
    txtLastName.Clear()
    txtEmployeeNumber.Clear()
    ComboBoxEmpDepartment.ResetText()
    txtTelephone.Clear()
    txtExtension.Clear()
    txtEmailAddress.Clear()

End Sub

Private Sub btnExit_Click(sender As Object, e As EventArgs) Handles btnExit.Click
    'Closes Program
    frmUserSelection.Show()
    Me.Visible = False
End Sub

Private Sub SaveFileDialog1_FileOk(sender As Object, e As System.ComponentModel.CancelEventArgs) Handles sfdSave.FileOk

End Sub

Private Sub PictureBox1_Click(sender As Object, e As EventArgs) Handles PictureBox1.Click
    'Picture Obtained From:
    '"User Add Icon-Shine Set: Add New User, Add User." Free Icons PNG. Accessed 14 October 2018. https://www.freeiconspng.com/img/2487
End Sub
End Class

1 个答案:

答案 0 :(得分:0)

Catch块仅在Try块内引发异常时才执行。我在这里看不到任何会导致这种情况发生的事情。看来您似乎对此有点误解。

请勿在{{1​​}}块中放入 validation 逻辑。如果发生一个异常,所有应该去的代码就是处理 exception 的代码。例如,如果由于数据库本身处于脱机状态而导致与数据库的连接失败,或者由于找不到/打开文件而导致写入文件失败。

在尝试进行保存之前,先放入您的 validation 逻辑。如果用户输入的验证失败,请不要尝试保存它。而是将错误返回给用户。仅当您的自定义验证通过时,您才可以开始Catch,写入数据存储,并在发生异常时处理异常。