我在查找Visual Basic课程的作业时遇到了一些麻烦。我被告知假设给定的文本文件不在我的程序的\ bin \ Debug文件夹中,所以我试图抛出异常错误并通过输入框从用户获取正确的路径,但似乎没有任何事情发生,或者变量没有设定,我不完全确定哪个。我有下面的代码,有关为什么这对我不起作用的任何提示?
谢谢!
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
Dim sr As IO.StreamReader
Dim age As Integer
Dim path As String
Try
sr = IO.File.OpenText("Ages.txt")
age = CInt(sr.ReadLine)
txtOutput.Text = "Age is " & age
Catch exc As IO.FileNotFoundException
path = InputBox("File Ages.txt not found." & vbCrLf & "Please enter the correct path to the file.", _
"Example: C:\Documents\My Text Files")
Catch exc As InvalidCastException
MessageBox.Show("File 'Ages.txt' contains an invalid age.", "Warning!")
Try
sr = IO.File.OpenText(path)
Finally
txtOutput.Text = "Age is " & age
End Try
Finally
Try
sr.Close()
Catch
End Try
End Try
End Sub
答案 0 :(得分:0)
你的内部Try / Catch块应该在FileNotFoundException catch中。
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
Dim sr As IO.StreamReader
Dim age As Integer
Dim path As String
Try
sr = IO.File.OpenText("Ages.txt")
age = CInt(sr.ReadLine)
txtOutput.Text = "Age is " & age
Catch exc As IO.FileNotFoundException
path = InputBox("File Ages.txt not found." & vbCrLf & "Please enter the correct path to the file.", _
"Example: C:\Documents\My Text Files")
Try
sr = IO.File.OpenText(path)
Finally
txtOutput.Text = "Age is " & age
End Try
Catch exc As InvalidCastException
MessageBox.Show("File 'Ages.txt' contains an invalid age.", "Warning!")
Finally
Try
sr.Close()
Catch
End Try
End Try
End Sub
更好的解决方案是......
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
Dim age As Integer
Dim path As String = "Ages.txt"
Dim fileFound As Boolean = False
While Not IO.File.Exists(path)
path = InputBox("File Ages.txt not found." & vbCrLf & "Please enter the correct path to the file.", _
"Example: C:\Documents\My Text Files")
End While
Using sr As IO.StreamReader = IO.File.OpenText(path)
If Integer.TryParse(sr.ReadLine, age) Then
txtOutput.Text = "Age is " & age
Else
MessageBox.Show("File 'Ages.txt' contains an invalid age.", "Warning!")
End If
End Using
End Sub
首先检查文件是否存在,然后继续循环,直到用户输入确实存在的文件为止。这允许您删除FileNotFoundException catch。
这也使用Integer.TryParse检查值是否正确转换,允许您删除InvalidCastException catch。
最后,使用Using语句打开阅读器消除了对finally /嵌套try-catch块的需要,因为Using在内部实现了它。
答案 1 :(得分:0)
我敢打赌,抛出的异常不是IO.FileNotFoundException
,因此您的InputBox
代码永远不会被命中。 OpenText
可以抛出相当多的异常类型。有几种方法你可以毫无例外地做到这一点(File.Exists浮现在脑海中),但是为了继续这条路线,我会将你的异常处理改为:
Catch exc as Exception
If TypeOf exc Is InvalidCastException Then
'...
Else
path = InputBox(....)
End If
End Try