【问题标题】:How to differentiate exceptions in Visual Basic如何区分 Visual Basic 中的异常
【发布时间】:2014-05-21 04:05:17
【问题描述】:

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

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。

【问题讨论】:

  • 一定要避免“catch-em-all”代码,必须生成一个体面的诊断结果将成为您的下一个问题。改为捕获 WebException。它的 Status 属性为您提供了与语言无关的错误提示。

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


【解决方案1】:

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

下面是例子:

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

【讨论】:

    【解决方案2】:

    如果您查看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 这样的一些异常有一个属性告诉你它是哪个错误号(例如Status

    【讨论】:

    • 虽然文档讲述了 WebException,但 Visual Studio 声称 Type 'Webexception' is not defined
    • @LorenzMeyer 您可能需要导入 System.Net 或输入 System.Net.WebException
    【解决方案3】:

    像这样使用带有多个 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
    

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

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

    希望对你有帮助

    【讨论】:

    • 谢谢,但这引发了下一个问题。我怎么知道我的前任会是InvalidCastException。调试时,是否有类似MsgBox(ex.ExceptionType) 的内容显示“InvalidCastException”?
    • 你可以使用'MsgBox(ex2.GetType().ToString())',它会显示一个包含'System.InvalidCastException'的消息框是你想要的吗?
    • 是的,这就是我要找的。 VB 还是很痛苦的,但至少这样可以一步一步往前走。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-30
    • 2019-09-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多