VB.NET中正确的异常处理

VB.NET中正确的异常处理,vb.net,exception-handling,Vb.net,Exception Handling,我一直在四处寻找我的问题的答案,但我没有找到太多答案,所以我在这里发帖,希望更有经验的开发人员能给我一些启发。在子系统中构造异常处理的正确方法是什么?我应该围绕我的整个代码块来包装我的Try、Catch、End Try,还是可以围绕我的子代码块中的一个代码块来包装Try、Catch、End Try,然后围绕同一子代码块中的另一个代码块来尝试、Catch、End Try?下面是我要问的一个例子: 这样更好吗?:(选项1) 试试看 '检查用户是否选择了文件 如果ListBoxPrePublish.S

我一直在四处寻找我的问题的答案,但我没有找到太多答案,所以我在这里发帖,希望更有经验的开发人员能给我一些启发。在子系统中构造异常处理的正确方法是什么?我应该围绕我的整个代码块来包装我的Try、Catch、End Try,还是可以围绕我的子代码块中的一个代码块来包装Try、Catch、End Try,然后围绕同一子代码块中的另一个代码块来尝试、Catch、End Try?下面是我要问的一个例子:

这样更好吗?:(选项1)

试试看
'检查用户是否选择了文件
如果ListBoxPrePublish.SelectedItems.Count=0,则
MessageBox.Show(“请选择要删除的文件”)
出口接头
如果结束
'检查用户是否选择了要发布的备忘录,如果选择了,请将文件移动到发布文件夹;如果用户尚未选择备注,请转到下一条if语句
如果ListBoxPrePublish.SelectedItem.Contains(“-M.xls”),则
Dim resultMemo=MessageBox.Show(“确实要删除此备忘录吗?”,“”,MessageBox按钮。是否)
如果resultMemo=DialogResult.Yes,则
Dim filePath As String=“W:\TOM\ERIC\Award\u Letters\Excel pre\u publish\”
Dim movePath As String=“W:\TOM\ERIC\Award\u Letters\Publish\”
Dim filenm As String=ListBoxPrePublish.SelectedItem
Dim FileToMove=filePath&filenm
Dim MoveToLocation=movePath&filenm
'移动文件
System.IO.File.Move(FileToMove、MoveToLocation)
ListBoxPublished.Items.Add(ListBoxPrePublish.SelectedItem)
ListBoxPrePublish.Items.Remove(ListBoxPrePublish.SelectedItem)
出口接头
其他的
出口接头
如果结束
如果结束
'询问用户是否确定要发布所选文件和相应的文件…记住,仅当所选项目不是备忘录时
Dim result=MessageBox.Show(“此操作将发布所选学生的所有相应文件,备忘录除外。备忘录必须单独删除。是否继续?”,“”,MessageBox按钮。是否)
如果result=DialogResult.No,则
出口接头
其他的
如果结果=DialogResult.Yes,则为
'在未批准的会计文件中查找学生ID,将记录移动到已删除的今天文件,从未批准的会计文件中删除记录
Dim UnapprovedActFile As String=“W:\TOM\ERIC\Award\U Letters\Accounting Files\Unapproved\”和StatVar.xlApp.Sheets(“新计算器输入”).Range(“D30”).Value&“xlsx”
Dim ApprovedAcctFile为String=“W:\TOM\ERIC\Award\U Letters\Accounting Files\Approved\”&StatVar.xlApp.Sheets(“新计算器输入”).Range(“D30”).Value&“Import”和“.xlsx”
Dim searchString As String=StatVar.xlApp.Sheets(“交叉检查”).Range(“J6”).Text“这是将在会计文件中搜索的ID
暗rng
'确保学校的会计档案存在
如果不存在IO.File.Exists(未批准的DCTFILE),则
MessageBox.Show(“找不到此学校的会计文件。请与管理员联系以获取帮助。”)
出口接头
如果结束
'打开会计文件并检查它是否为只读,如果是,另一个用户正在编辑它,请关闭它并告诉用户几秒钟后重试,如果不是只读的,请参阅下一条评论
StatVar.xlwUnapprovedACTFile=StatVar.xlApp.Workbooks.Open(UnapprovedACTFile)
如果StatVar.xlApp.ActiveWorkbook.ReadOnly=True,则“检查文件是否为只读,如果为只读,则将其关闭并退出子文件”
StatVar.xlApp.ActiveWorkbook.Close(False)
MessageBox.Show(“系统正忙。请几秒钟后重试。”)
出口接头
如果结束
'搜索未批准的会计文件以查找ID(SSN奖励年度示例:555-13)-使用上面的searchString变量
rng=StatVar.xlApp.ActiveWorkbook.Sheets(“Sheet1”).Range(“BD2:BD30002”).Find(搜索字符串,Excel.XlFindLookIn.xlValues,Excel.XlLookAt.xlWhole,Excel.XlSearchOrder.xlByRows,Excel.XlSearchDirection.xlNext,False)
'如果找到searchString
如果rng不是什么,那么
rng.EntireRow.Select()'选择在中找到的行搜索字符串
'检查此学校是否存在已批准的会计文件,如果不存在,请创建它
如果不存在IO.File.Exists(ApprovedAcctFile),则
StatVar.xlApp.Workbooks.Add()
StatVar.xlApp.ActiveWorkbook.SaveAs(ApprovedAcctFile)
StatVar.xlApp.ActiveWorkbook.Close(True)
如果结束
StatVar.xlwbapprovedacttfile=StatVar.xlApp.Workbooks.Open(Approvedacttfile)'打开已批准的文件
如果StatVar.xlApp.ActiveWorkbook.ReadOnly=True,则“检查批准的文件是否为只读,如果是,请关闭该文件并退出sub,因为它需要可写
StatVar.xlApp.ActiveWorkbook.Close(False)'关闭已批准的文件,不保存更改
StatVar.xlApp.ActiveWorkbook.Close(False)'关闭未批准的会计文件,不保存更改
MessageBox.Show(“系统正忙。请几秒钟后重试。”)
出口接头
如果结束
StatVar.xlApp.ActiveWorkbook.ActiveSheet.Columns(“AV”).NumberFormat=“@”将已批准文件的AV列格式化为文本,以便“13/14”保持正确格式
StatVar.xlApp.ActiveWorkbook.ActiveSheet.Rows(“1:1”).Insert(Excel.XlInsertShiftDirection.xlShiftDown)”在批准的文件顶部插入一行
StatVar.xlApp.ActiveWo
Try
        'check if user has selected a file
        If ListBoxPrePublish.SelectedItems.Count = 0 Then
            MessageBox.Show("Please select a file to delete.")
            Exit Sub
        End If

        'check if user has selected a Memo to publish, if so, move file to Publish folder; if user hasn't selected a Memo, move to next If statement
        If ListBoxPrePublish.SelectedItem.Contains("-M.xls") Then
            Dim resultMemo = MessageBox.Show("Are you sure you want to delete this Memo?", "", MessageBoxButtons.YesNo)
            If resultMemo = DialogResult.Yes Then
                Dim filePath As String = "W:\TOM\ERIC\Award_Letters\Excel pre_publish\"
                Dim movePath As String = "W:\TOM\ERIC\Award_Letters\Publish\"
                Dim filenm As String = ListBoxPrePublish.SelectedItem
                Dim FileToMove = filePath & filenm
                Dim MoveToLocation = movePath & filenm
                'move the file
                System.IO.File.Move(FileToMove, MoveToLocation)
                ListBoxPublished.Items.Add(ListBoxPrePublish.SelectedItem)
                ListBoxPrePublish.Items.Remove(ListBoxPrePublish.SelectedItem)
                Exit Sub
            Else
                Exit Sub
            End If
        End If



        'ask user if they're sure they want to publish selected file and corresponding files...remember, only if the selected item is not a Memo
        Dim result = MessageBox.Show("This action will publish all corresponding files for the selected student except for Memos. Memos must be deleted individually. Do you want to continue?", "", MessageBoxButtons.YesNo)
        If result = DialogResult.No Then
            Exit Sub
        Else

            If result = DialogResult.Yes Then
                'find ID for student in unapprovd accounting file, move the record to the Deleted Today file, delete record from unapproved accounting file
                Dim UnapprovedAcctFile As String = "W:\TOM\ERIC\Award_Letters\Accounting Files\Unapproved\" & StatVar.xlApp.Sheets("New Calculator Input").Range("D30").Value & ".xlsx"
                Dim ApprovedAcctFile As String = "W:\TOM\ERIC\Award_Letters\Accounting Files\Approved\" & StatVar.xlApp.Sheets("New Calculator Input").Range("D30").Value & " Import" & ".xlsx"
                Dim searchString As String = StatVar.xlApp.Sheets("Cross Checking").Range("J6").Text 'this is the ID that will be searched for in the accounting file
                Dim rng

                'make sure accounting file for school exists
                If Not IO.File.Exists(UnapprovedAcctFile) Then
                    MessageBox.Show("Could not locate the accounting file for this school. Please contact an administrator for assistance.")
                    Exit Sub
                End If

                'open accounting file and check if it's read only, if so, another user is editing it so close it and tell the user to try again in a few seconds, if it's not read only, see next comment
                StatVar.xlWBUnapprovedAcctFile = StatVar.xlApp.Workbooks.Open(UnapprovedAcctFile)
                If StatVar.xlApp.ActiveWorkbook.ReadOnly = True Then 'check if file is read only, if so close it and exit sub
                    StatVar.xlApp.ActiveWorkbook.Close(False)
                    MessageBox.Show("The system is busy. Please try again in a few seconds.")
                    Exit Sub
                End If

                'search unapproved accounting file for ID (SSN-award year example: 555555555-13) - use searchString variable above
                rng = StatVar.xlApp.ActiveWorkbook.Sheets("Sheet1").Range("BD2:BD30002").Find(searchString, , Excel.XlFindLookIn.xlValues, Excel.XlLookAt.xlWhole, Excel.XlSearchOrder.xlByRows, Excel.XlSearchDirection.xlNext, False)
                'if searchString is found
                If rng IsNot Nothing Then
                    rng.EntireRow.Select() 'select the row searchString was found in
                    'check if approved accounting file for this school exists, if not, create it
                    If Not IO.File.Exists(ApprovedAcctFile) Then
                        StatVar.xlApp.Workbooks.Add()
                        StatVar.xlApp.ActiveWorkbook.SaveAs(ApprovedAcctFile)
                        StatVar.xlApp.ActiveWorkbook.Close(True)
                    End If
                    StatVar.xlWBApprovedAcctFile = StatVar.xlApp.Workbooks.Open(ApprovedAcctFile) 'open the Approved file
                    If StatVar.xlApp.ActiveWorkbook.ReadOnly = True Then 'check if the Approved file is read only, if so, close it and exit sub because it needs to be writable
                        StatVar.xlApp.ActiveWorkbook.Close(False) 'close the Approved file, don't save changes
                        StatVar.xlApp.ActiveWorkbook.Close(False) 'close unapproved accounting file, don't save changes
                        MessageBox.Show("The system is busy. Please try again in a few seconds.")
                        Exit Sub
                    End If
                    StatVar.xlApp.ActiveWorkbook.ActiveSheet.Columns("AV").NumberFormat = "@" 'format column AV of the Approved file as text so "13/14" remains formatted correctly
                    StatVar.xlApp.ActiveWorkbook.ActiveSheet.Rows("1:1").Insert(Excel.XlInsertShiftDirection.xlShiftDown) 'insert a row at the top of the Approved file
                    StatVar.xlApp.ActiveWorkbook.ActiveSheet.Rows("1:1").Value = rng.EntireRow.Value 'set the 1st row of the Approved file equal to the row selected earlier in the unapproved accounting file
                    StatVar.xlApp.ActiveWorkbook.ActiveSheet.UsedRange.RemoveDuplicates(Columns:=(56)) 'search column 56 in Approved file for duplicates and remove entire row if a duplicate ID is found
                    rng.EntireRow.Delete() 'delete row the searchString was found in from the unapproved accounting file
                    StatVar.xlApp.ActiveWorkbook.Close(True) 'close the Approved file, save changes
                    StatVar.xlApp.ActiveWorkbook.Close(True) 'close unapproved accounting file, save changes
                    'MessageBox.Show("Eureka!")
                Else
                    'if searchString is not found, close unapproved accounting file, inform user and exit sub
                    StatVar.xlApp.ActiveWorkbook.Close(False)
                    MessageBox.Show("Could not locate this record on the accounting file. Your files were not deleted.")
                    Exit Sub
                End If

                'move selected file and corresponding non-Memo files to Publish folder
                Dim filePath As String = "W:\TOM\ERIC\Award_Letters\Excel pre_publish\"
                Dim movePath As String = "W:\TOM\ERIC\Award_Letters\Publish\"
                Dim filenm As String

                'check if each item in listbox contains the string extracted from the selected item via Excel formula; listbox select event sends the filename to Excel and a formula extracts the string to find in each listbox item...look for this string
                For Each c In ListBoxPrePublish.Items
                    If c.ToString.Contains(StatVar.xlApp.Sheets("Cross Checking").Range("H6").Text) Then
                        'make sure the current listbox item in this loop is not a Memo, if it's not, move it
                        If Not c.ToString.Contains("-M.xls") Then
                            filenm = c
                            Dim FileToMove = filePath & filenm
                            Dim MoveToLocation = movePath & filenm
                            System.IO.File.Move(FileToMove, MoveToLocation)
                            ListBoxPublished.Items.Add(c) 'add files files that are being published to the published files listbox
                        End If
                    End If
                Next

                'refresh prepublish list, if user has a school selected, REMOVE all list items that don't contain the school code being generated via VLOOKUP in Excel using the school name from comboboxschool; look for this string in the loop surrounded with "-"
                Call ListFiles()
                If ComboBoxSchool.Text <> "" Then
                    For i As Integer = ListBoxPrePublish.Items.Count - 1 To 0 Step -1
                        'if current loop item does not contain the school code for the selected school, remove the item from the listbox
                        If Not ListBoxPrePublish.Items(i).Contains("-" & StatVar.xlApp.Sheets("Cross Checking").Range("E3").Text & "-") Then
                            ListBoxPrePublish.Items.RemoveAt(i)
                        End If
                    Next
                End If
                'refresh deleted files listbox
                Call ListDeletedTodayFiles()

            End If
        End If
    Catch exc As Exception
        MessageBox.Show("Unable to publish the selected file. Please verify this file or any of its corresponding files are not open by you or another user. If the problem persists, contact an administrator for assistance." & vbNewLine & vbNewLine & "Error: " & exc.Message)
    End Try
 Try
        'check if user has selected a file
        If ListBoxPrePublish.SelectedItems.Count = 0 Then
            MessageBox.Show("Please select a file to delete.")
            Exit Sub
        End If

        'check if user has selected a Memo to publish, if so, move file to Publish folder; if user hasn't selected a Memo, move to next If statement
        If ListBoxPrePublish.SelectedItem.Contains("-M.xls") Then
            Dim resultMemo = MessageBox.Show("Are you sure you want to delete this Memo?", "", MessageBoxButtons.YesNo)
            If resultMemo = DialogResult.Yes Then
                Dim filePath As String = "W:\TOM\ERIC\Award_Letters\Excel pre_publish\"
                Dim movePath As String = "W:\TOM\ERIC\Award_Letters\Publish\"
                Dim filenm As String = ListBoxPrePublish.SelectedItem
                Dim FileToMove = filePath & filenm
                Dim MoveToLocation = movePath & filenm
                'move the file
                System.IO.File.Move(FileToMove, MoveToLocation)
                ListBoxPublished.Items.Add(ListBoxPrePublish.SelectedItem)
                ListBoxPrePublish.Items.Remove(ListBoxPrePublish.SelectedItem)
                Exit Sub
            Else
                Exit Sub
            End If
        End If
    Catch exc As Exception
        MessageBox.Show("An error occured and the selected file was not published. Please contact an administrator if the problem continues." & vbNewLine & vbNewLine & "Error: " & exc.Message)
    End Try

    Try
        'ask user if they're sure they want to publish selected file and corresponding files...remember, only if the selected item is not a Memo
        Dim result = MessageBox.Show("This action will publish all corresponding files for the selected student except for Memos. Memos must be deleted individually. Do you want to continue?", "", MessageBoxButtons.YesNo)
        If result = DialogResult.No Then
            Exit Sub
        Else

            If result = DialogResult.Yes Then
                'find ID for student in unapprovd accounting file, move the record to the Deleted Today file, delete record from unapproved accounting file
                Dim UnapprovedAcctFile As String = "W:\TOM\ERIC\Award_Letters\Accounting Files\Unapproved\" & StatVar.xlApp.Sheets("New Calculator Input").Range("D30").Value & ".xlsx"
                Dim ApprovedAcctFile As String = "W:\TOM\ERIC\Award_Letters\Accounting Files\Approved\" & StatVar.xlApp.Sheets("New Calculator Input").Range("D30").Value & " Import" & ".xlsx"
                Dim searchString As String = StatVar.xlApp.Sheets("Cross Checking").Range("J6").Text 'this is the ID that will be searched for in the accounting file
                Dim rng

                'make sure accounting file for school exists
                If Not IO.File.Exists(UnapprovedAcctFile) Then
                    MessageBox.Show("Could not locate the accounting file for this school. Please contact an administrator for assistance.")
                    Exit Sub
                End If

                'open accounting file and check if it's read only, if so, another user is editing it so close it and tell the user to try again in a few seconds, if it's not read only, see next comment
                StatVar.xlWBUnapprovedAcctFile = StatVar.xlApp.Workbooks.Open(UnapprovedAcctFile)
                If StatVar.xlApp.ActiveWorkbook.ReadOnly = True Then 'check if file is read only, if so close it and exit sub
                    StatVar.xlApp.ActiveWorkbook.Close(False)
                    MessageBox.Show("The system is busy. Please try again in a few seconds.")
                    Exit Sub
                End If

                'search unapproved accounting file for ID (SSN-award year example: 555555555-13) - use searchString variable above
                rng = StatVar.xlApp.ActiveWorkbook.Sheets("Sheet1").Range("BD2:BD30002").Find(searchString, , Excel.XlFindLookIn.xlValues, Excel.XlLookAt.xlWhole, Excel.XlSearchOrder.xlByRows, Excel.XlSearchDirection.xlNext, False)
                'if searchString is found
                If rng IsNot Nothing Then
                    rng.EntireRow.Select() 'select the row searchString was found in
                    'check if approved accounting file for this school exists, if not, create it
                    If Not IO.File.Exists(ApprovedAcctFile) Then
                        StatVar.xlApp.Workbooks.Add()
                        StatVar.xlApp.ActiveWorkbook.SaveAs(ApprovedAcctFile)
                        StatVar.xlApp.ActiveWorkbook.Close(True)
                    End If
                    StatVar.xlWBApprovedAcctFile = StatVar.xlApp.Workbooks.Open(ApprovedAcctFile) 'open the Approved file
                    If StatVar.xlApp.ActiveWorkbook.ReadOnly = True Then 'check if the Approved file is read only, if so, close it and exit sub because it needs to be writable
                        StatVar.xlApp.ActiveWorkbook.Close(False) 'close the Approved file, don't save changes
                        StatVar.xlApp.ActiveWorkbook.Close(False) 'close unapproved accounting file, don't save changes
                        MessageBox.Show("The system is busy. Please try again in a few seconds.")
                        Exit Sub
                    End If
                    StatVar.xlApp.ActiveWorkbook.ActiveSheet.Columns("AV").NumberFormat = "@" 'format column AV of the Approved file as text so "13/14" remains formatted correctly
                    StatVar.xlApp.ActiveWorkbook.ActiveSheet.Rows("1:1").Insert(Excel.XlInsertShiftDirection.xlShiftDown) 'insert a row at the top of the Approved file
                    StatVar.xlApp.ActiveWorkbook.ActiveSheet.Rows("1:1").Value = rng.EntireRow.Value 'set the 1st row of the Approved file equal to the row selected earlier in the unapproved accounting file
                    StatVar.xlApp.ActiveWorkbook.ActiveSheet.UsedRange.RemoveDuplicates(Columns:=(56)) 'search column 56 in Approved file for duplicates and remove entire row if a duplicate ID is found
                    rng.EntireRow.Delete() 'delete row the searchString was found in from the unapproved accounting file
                    StatVar.xlApp.ActiveWorkbook.Close(True) 'close the Approved file, save changes
                    StatVar.xlApp.ActiveWorkbook.Close(True) 'close unapproved accounting file, save changes
                    'MessageBox.Show("Eureka!")
                Else
                    'if searchString is not found, close unapproved accounting file, inform user and exit sub
                    StatVar.xlApp.ActiveWorkbook.Close(False)
                    MessageBox.Show("Could not locate this record on the accounting file. Your files were not deleted.")
                    Exit Sub
                End If

                'move selected file and corresponding non-Memo files to Publish folder
                Dim filePath As String = "W:\TOM\ERIC\Award_Letters\Excel pre_publish\"
                Dim movePath As String = "W:\TOM\ERIC\Award_Letters\Publish\"
                Dim filenm As String

                'check if each item in listbox contains the string extracted from the selected item via Excel formula; listbox select event sends the filename to Excel and a formula extracts the string to find in each listbox item...look for this string
                For Each c In ListBoxPrePublish.Items
                    If c.ToString.Contains(StatVar.xlApp.Sheets("Cross Checking").Range("H6").Text) Then
                        'make sure the current listbox item in this loop is not a Memo, if it's not, move it
                        If Not c.ToString.Contains("-M.xls") Then
                            filenm = c
                            Dim FileToMove = filePath & filenm
                            Dim MoveToLocation = movePath & filenm
                            System.IO.File.Move(FileToMove, MoveToLocation)
                            ListBoxPublished.Items.Add(c) 'add files files that are being published to the published files listbox
                        End If
                    End If
                Next

                'refresh prepublish list, if user has a school selected, REMOVE all list items that don't contain the school code being generated via VLOOKUP in Excel using the school name from comboboxschool; look for this string in the loop surrounded with "-"
                Call ListFiles()
                If ComboBoxSchool.Text <> "" Then
                    For i As Integer = ListBoxPrePublish.Items.Count - 1 To 0 Step -1
                        'if current loop item does not contain the school code for the selected school, remove the item from the listbox
                        If Not ListBoxPrePublish.Items(i).Contains("-" & StatVar.xlApp.Sheets("Cross Checking").Range("E3").Text & "-") Then
                            ListBoxPrePublish.Items.RemoveAt(i)
                        End If
                    Next
                End If
                'refresh deleted files listbox
                Call ListDeletedTodayFiles()

            End If
        End If
    Catch exc As Exception
        MessageBox.Show("Unable to publish the selected file. Please verify this file or any of its corresponding files are not open by you or another user. If the problem persists, contact an administrator for assistance." & vbNewLine & vbNewLine & "Error: " & exc.Message)
    End Try