我的异常处理策略是:
然后我总是将在外部运行的每一段代码包含在try/catch 中:
- WinForms 基础结构触发的所有事件(Load、Click、SelectedChanged...)
- 第三方组件触发的所有事件
然后我用'try/catch'括起来
- 我知道的所有操作可能不会一直有效(IO 操作、可能进行零除法的计算...)。在这种情况下,我会抛出一个新的
ApplicationException("custom message", innerException) 来跟踪实际发生的情况
此外,我尽我所能正确地对异常进行排序。有以下例外情况:
在应用程序顶级错误处理程序中设计一些静态方法来处理异常是一种很好的做法。
我也强迫自己尝试:
- 请记住所有异常都会冒泡到顶层。没有必要在任何地方都放置异常处理程序。
- 可重用或深度调用的函数不需要显示或记录异常:它们要么自动冒泡,要么在我的异常处理程序中使用一些自定义消息重新抛出。
最后:
不好:
// DON'T DO THIS; ITS BAD
try
{
...
}
catch
{
// only air...
}
没用的:
// DON'T DO THIS; IT'S USELESS
try
{
...
}
catch(Exception ex)
{
throw ex;
}
在没有捕获的情况下尝试 finally 是完全有效的:
try
{
listView1.BeginUpdate();
// If an exception occurs in the following code, then the finally will be executed
// and the exception will be thrown
...
}
finally
{
// I WANT THIS CODE TO RUN EVENTUALLY REGARDLESS AN EXCEPTION OCCURRED OR NOT
listView1.EndUpdate();
}
我在顶层做什么:
// i.e When the user clicks on a button
try
{
...
}
catch(Exception ex)
{
ex.Log(); // Log exception
-- OR --
ex.Log().Display(); // Log exception, then show it to the user with apologies...
}
我在一些被调用的函数中做了什么:
// Calculation module
try
{
...
}
catch(Exception ex)
{
// Add useful information to the exception
throw new ApplicationException("Something wrong happened in the calculation module:", ex);
}
// IO module
try
{
...
}
catch(Exception ex)
{
throw new ApplicationException(string.Format("I cannot write the file {0} to {1}", fileName, directoryName), ex);
}
与异常处理(自定义异常)有很多关系,但我尝试记住的那些规则对于我所做的简单应用程序来说已经足够了。
这里是一个扩展方法的示例,可以以一种舒适的方式处理捕获的异常。它们以可以链接在一起的方式实现,并且很容易添加您自己捕获的异常处理。
// Usage:
try
{
// boom
}
catch(Exception ex)
{
// Only log exception
ex.Log();
-- OR --
// Only display exception
ex.Display();
-- OR --
// Log, then display exception
ex.Log().Display();
-- OR --
// Add some user-friendly message to an exception
new ApplicationException("Unable to calculate !", ex).Log().Display();
}
// Extension methods
internal static Exception Log(this Exception ex)
{
File.AppendAllText("CaughtExceptions" + DateTime.Now.ToString("yyyy-MM-dd") + ".log", DateTime.Now.ToString("HH:mm:ss") + ": " + ex.Message + "\n" + ex.ToString() + "\n");
return ex;
}
internal static Exception Display(this Exception ex, string msg = null, MessageBoxImage img = MessageBoxImage.Error)
{
MessageBox.Show(msg ?? ex.Message, "", MessageBoxButton.OK, img);
return ex;
}