【问题标题】:Can VB.NET catch exceptions without defining a local exception variable?VB.NET 可以在不定义局部异常变量的情况下捕获异常吗?
【发布时间】:2011-04-06 18:01:28
【问题描述】:

在 C# 中你可以这样做:

try
{
    // some code here
}
catch (MyCustomException)
{
    // exception code here
}
catch (Exception)
{
    // catches all other exceptions
}

注意catch (Type) 而不是catch (Type myVariable)。这在 VB.NET 中是否可行,还是在捕获异常类型时总是必须声明一个变量,如下所示:

    Try
        ...
    Catch var As NullReferenceException
        ...
    Catch var As Exception
        ...
    End Try

【问题讨论】:

    标签: vb.net exception-handling c#-to-vb.net


    【解决方案1】:

    必须在 vb.net 中声明。 事实上,当您输入try 时,您的 ide 应该输入异常类型并对其进行格式化。

    像这样:

    Try
    Catch e As Exception
    End Try
    

    【讨论】:

    • 而且 VB.NET 不会给你 变量 'ex' 已声明但从未使用 警告,如果你声明它并且不这样做,你会在 C# 中得到警告使用它。
    • 是的,Visual Studio 就是这样做的,这正是我所害怕的。我将把它放在我的“C# 擅长的事物列表”中。谢谢。 :)
    • @SpikeX - VB.net 真的很罗嗦。
    • 我使用它是因为我必须这样做,而不是因为我想这样做。 ;)
    • @SimenS Visual Studio 给了我对 VB.NET 的警告。
    【解决方案2】:

    万一搜索引擎把其他人带到这里......

    C# 还有一种语法,您不必指定类型:

    try { }
    catch { }
    

    我相信这也会捕获不是从 System.Exception 派生的非托管异常。 VB.NET 也可以这样做:

    Try
    Catch
    End Try
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-10-12
      • 1970-01-01
      • 1970-01-01
      • 2011-05-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-25
      • 2011-06-16
      相关资源
      最近更新 更多