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

为什么resharper说这是多余的?

try
{
    File.Open("FileNotFound.txt", FileMode.Open);
}
catch
{
    throw;
}
有帮助吗?

解决方案

由于

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);
}

不会多余。

其他提示

因为上面的语句具有与不存在相同的行为。与写作相同:

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

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

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

因为它是多余的。

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

它警告你,因为没有必要尝试......抓住那里。

另外,另一个好的提示是“抛出前”。不会保留堆栈跟踪但是“抛出”将

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

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

...是还原剂,以下不是......

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

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

祝你好运调试代码!

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top