20

我认为抛出异常是一种很好的做法,可以让它冒泡到 UI 或记录异常并通知用户的地方。

为什么 resharper 说它是多余的?

try
{
    File.Open("FileNotFound.txt", FileMode.Open);
}
catch
{
    throw;
}
4

6 回答 6

57

因为

try {
    File.Open("FileNotFound.txt", FileMode.Open);
} catch {
    throw;
}

没有什么不同

File.Open("FileNotFound.txt", FileMode.Open);

如果调用File.Open(string, FileMode)失败,那么在任一示例中,完全相同的异常都会到达 UI。

在上面的那个catch子句中,您只是捕获并重新抛出异常,而无需执行任何其他操作,例如记录日志、回滚事务、包装异常以向其添加附加信息或任何其他操作。

然而,

try {
    File.Open("FileNotFound.txt", FileMode.Open);
} catch(Exception ex) {
    GetLogger().LogException(ex);
    throw;
}

不会包含任何冗余,ReSharper 不应抱怨。同样地,

try {
    File.Open("FileNotFound.txt", FileMode.Open);
} catch(Exception ex) {
    throw new MyApplicationException(
        "I'm sorry, but your preferences file could not be found.", ex);
}

不会是多余的。

于 2009-06-19T17:58:03.853 回答
17

因为上面的语句具有与不存在相同的行为。和写法一样:

File.Open("FileNotFound.txt", FileMode.Open);
于 2009-06-19T17:56:28.003 回答
5

因为它是多余的。

于 2009-06-19T18:00:08.607 回答
4

因为 try 中的代码已经在抛出异常。

如果除了重新抛出异常之外,您还打算在 catch 块中执行其他操作时,您只想捕获并重新抛出异常。

于 2009-06-19T17:58:08.033 回答
1

你在catch块中没有做任何处理,只是再次抛出了异常。

它会警告您,因为在那里设置 try...catch 块是没有意义的。

另外,另一个很好的提示是“throw ex”不会保留堆栈跟踪,但“throw”会。

于 2009-06-19T17:58:21.433 回答
1

值得注意的是,虽然...

try
{
    DoSomething();
}
catch
{
    throw;
}

...是多余的,以下不是...

try
{
    DoSomething();
}
catch (Exception ex)
{
    // Generally a very bad idea!
    throw ex;
}

第二个代码片段在我之前继承的几个项目的代码库中很常见,它具有隐藏原始异常堆栈跟踪的讨厌效果。以这种方式抛出刚刚捕获的异常意味着堆栈跟踪的顶部处于该throw级别,没有提及DoSomething或实际上导致异常的任何嵌套方法调用。

祝你调试代码好运!

于 2009-07-23T08:17:55.310 回答