在 try/catch 块中避免警告 "variable is declared but never used"

Avoiding warning "variable is declared but never used" in try/catch block

给定以下 C# 代码:

public void CatchExceptionThenThrow()
{
    try
    {
        StartThings();
    }
    catch (Exception)
    {
        throw;
    }
}

我已经使用 dotnetfiddle VB.net 转换器将其转换为 VB:

Public Sub CatchExceptionThenThrow()
    Try
        StartThings()
    Catch As Exception
        Throw
    End Try
End Sub

这会引发编译错误:

Catch As Exception

End of Statement expected

然后我将其更改为:

Public Sub CatchExceptionThenThrow()
    Try
        StartThings()
    Catch ex As Exception
        Throw
    End Try
End Sub

但这会产生警告 "variable declared but never used"。我如何在没有收到警告的情况下在 throwing 而不是 throw exing VB,同时保留第一个 C# 示例中的整个堆栈跟踪?


所有好的评论,感谢您提供的冗余信息我意识到 try/catch 是完全不需要的,因为无论有没有 try/catch 都会发生这种情况。这个问题更多是出于好奇,我认为在(好的代码)现实中没有真正的基础。

我最近在博客 post 中看到了关于异常处理的类似内容,以及为什么要 throwthrow ex,只是好奇如何在VB - 因为我不擅长 VB 并且正在尝试更好地理解它和异常处理。

我曾希望能够找到上面提到的博客 post,但找不到了。可以找到它的要点(产生问题):https://dotnetfiddle.net/741wAi

只要有一个空的 Catch 比如:

Try
     StartThings()
Catch
    Throw
End Try

但是如果你在 Catch 块中除了重新抛出它之外没有做任何事情,那么将 try-catch 放在首位是没有意义的。

您可以 StartThings() 不使用 try-catch,如果出现异常,异常将传播给调用者。

您收到 Catch ex As Exception 警告的原因是您在变量 ex 中捕获了异常,但您没有在任何地方使用它。

如果您只是捕捉 Exception 那么您的代码是多余的,正如已经指出的那样。但是,如果您正在简化您的示例代码并且您试图仅捕获特定类型的异常并对其他抛出的 Exception 进行其他处理,那么我不想向您打破它但它出现 VB 不能真正做到这一点,所以你必须忍受警告。显然不要抛出 ex.