问题描述
我以为抛出异常是一个很好的做法,让它弹回到UI或者你记录例外的地方,并通知用户。
I thought throwing an exception is good practice to let it bubble back up to the UI or somewhere where you log the exception and notify the user about it.
为什么复习者说这是多余的吗?
Why does resharper say it is redundant?
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。
If the call to File.Open(string, FileMode)
fails, then in either sample the exact same exception will find its way up to the UI.
在 catch
子句,您只需捕获并重新抛出异常,而无需执行任何其他操作,例如日志记录,回滚事务,包装异常以向其添加其他信息,或任何其他信息。
In that catch
clause above, you are simply catching and re-throwing an exception without doing anything else, such as logging, rolling back a transaction, wrapping the exception to add additional information to it, or anything at all.
但是,
try {
File.Open("FileNotFound.txt", FileMode.Open);
} catch(Exception ex) {
GetLogger().LogException(ex);
throw;
}
不会包含任何冗余,ReSharper不应该抱怨。同样地,
would not contain any redundancies and ReSharper should not complain. Likewise,
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);
}
不会多余。
这篇关于为什么resharper说'Catch子句与单'throw'语句是多余的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!