如何区分Visual Basic中的异常

时间:2014-04-08 12:42:56

标签: vb.net exception visual-studio-2008 exception-handling try-catch

我正在尝试使用以下代码下载文件:

Try
    My.Computer.Network.DownloadFile _
        (fileUrl, Path.Combine(mySettings.filePath, fileName), _
        "", "", False, 500, True)
Catch ex As Exception
    MsgBox(translation.GetString("msgNavError") & vbCrLf & ex.Message)
End Try

此代码有效并显示Le nom distant n'a pas pu être résolu: '<hostname>'之类的错误。比较像If ex.Message = "Le nom distant n'a pas pu être résolu: '<hostname>'" Then ...这样没有意义,因为消息是本地化的。

那我怎么能在VB.net中写这个伪代码呢?

Catch ex As Exception
    If ex.NoNetworkWorkConnection Then
        MsgBox("Your computer is not connected to the network")
    Else If ex.ServerDidntRespond Then
        MsgBox("The server did not respond")
    Else
        MsgBox("Unexpected error : " & ex.Message)
    End If
End Try

我正在使用Visual Basic 2008 Express。

3 个答案:

答案 0 :(得分:2)

使用带有多个catch子句的try语句,如此

Try
'insert exception prone code here    
Throw New OutOfMemoryException
Throw New InvalidCastException

Catch ex As OutOfMemoryException
    Console.WriteLine("out of memory")

Catch ex2 As InvalidCastException
    Console.WriteLine("invalid cast")
End Try

然后,如果抛出内存不足异常,如果抛出无效的强制转换异常,将执行1st catch子句,将执行第二个catch子句。

您可以将异常类型更改为适合您需要的类型,因为这只是一个示例

希望这有帮助

答案 1 :(得分:1)

如果查看DownloadFile的帮助页面,您将看到抛出的异常列表(ArgumentException,IOException,TimeoutException,SecurityException,WebException)。抓住你想要的那个,而不是抓住一般的例外。

Try
    My.Computer.Network.DownloadFile _
        (fileUrl, Path.Combine(mySettings.filePath, fileName), _
        "", "", False, 500, True)


Catch ex As ArgumentException
    MsgBox("ArgumentException")
Catch ex2 As IOException
    MsgBox("IOException")
End Try

像WebException这样的异常有一个属性告诉你它是哪个错误号(ex Status

答案 2 :(得分:1)

您可以使用TypeOf关键字...

以下是示例:

Try
    CODEZ HERE
Catch ex As Exception
    If TypeOf ex Is OutOfMemoryException Then
        MsgBox("Out of memory exception")
    End If
End Try