对于Visual Basic 2015中不是VB.NET的以下代码,我遇到了“找不到文件”异常:
path = "c:\winpython\codes\output.TXT"
Dim sr2 As System.IO.StreamReader = New System.IO.StreamReader(path)
如何捕获此错误并向用户显示适当的消息,要求他们不要删除该文件?
最佳答案
这是在Visual Basic 2015中捕获“文件未找到”异常的方法:
Try
path = "c:\winpython\codes\output.TXT"
Dim sr2 As System.IO.StreamReader = New System.IO.StreamReader(path)
Catch ex As FileNotFoundException
MessageBox.Show(ex.Message)
Catch ex As Exception
MsgBox(ex.Message)
End Try
请记住,除了“找不到文件异常”之外,在打开文件时还可能会遇到其他异常。因此,最后一个异常(exception)是Catch。
您可以将ex.Message替换为想要显示给用户的自己的String消息,如下所示:
Catch ex As Exception
MsgBox("There is an error while opening the File")
希望这可以帮助。
关于visual-studio-2015 - 如何在Visual Basic 2015中捕获异常而不是VB.NET,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44534469/