我在很多地方都看到过这样的代码,这样做有什么好处..或者这是一种错误的做法..
try
{
......
}
catch (NullReferenceException ex)
{
Data.LogError(ex, "Exception occourred while ...");
}
catch (IndexOutOfRangeException ex)
{
Data.LogError(ex, "Exception occourred while ...");
}
catch (Exception ex)
{
Data.LogError(ex, "Exception occourred while ...");
}
在特定异常处理的上下文中。
最佳答案
如果您打算在 catch block 中以不同的方式处理异常(即,由于抛出异常而执行不同的操作),这会有好处。
否则你可以删除更具体的异常处理程序并只使用最通用的:
catch(Exception ex)
注意:如果异常纯粹用于日志记录,那么有时重新抛出异常以将其冒泡到应用程序的其余部分可能很有用:
try{
}
catch(Exception ex){
// Log exception here
throw;
}
关于c# - 像这样处理特定异常是否可以,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16833098/