我的异常处理策略是:
要通过钩住捕获 所有未处理的异常
Application.ThreadException event
,然后决定:- 对于UI应用程序:使用道歉消息将其弹出给用户(winforms)
- 对于服务或控制台应用程序:将其记录到文件(服务或控制台)中
然后,我总是将 在外部运行的所有代码 都包含在
try/catch:
- Winforms基础结构触发的所有事件(加载,单击,SelectedChanged …)
- 第三方组件触发的所有事件
然后我附上“ try / catch”
- 我 知道的 所有 操作 可能并非一直都有效 (IO操作,潜在的零除法计算…)。在这种情况下,我会抛出一个新事件
ApplicationException("custom message", innerException)来跟踪实际发生的情况
另外,我会尽力 正确地对异常 进行 排序 。有以下例外情况:
- 需要立即向用户显示
- 需要一些额外的处理,以便在事情发生时将它们放在一起,以避免级联问题(即:
finally
在TreeView
填充过程中将.EndUpdate放在该部分中) 用户不在乎,但重要的是要知道发生了什么。所以我总是记录它们:
- 在事件日志中
- 或磁盘上的.log文件中
设计一些静态方法来处理 应用程序顶级错误处理程序中的 异常 是一个好习惯。
我也强迫自己尝试:
- 请记住, 所有异常都会冒泡到顶层 。不必将异常处理程序放在各处。
- 可重用或深度调用的函数不需要显示或记录异常:它们要么自动冒泡,要么在我的异常处理程序中随一些自定义消息重新抛出。
所以最后:
坏:
// DON'T DO THIS, ITS BADtry{ ...}catch { // only air...}无用:
// DONT'T DO THIS, ITS USELESStry{ ...}catch(Exception ex){ throw ex;}最终尝试而没有抓住是完全有效的:
try{ listView1.BeginUpdate(); // If an exception occurs in the following pre, then the finally will be executed // and the exception will be thrown ...}finally{ // I WANT THIS CODE TO RUN EVENTUALLY REGARDLESS AN EXCEPTION OCCURED OR NOT listView1.EndUpdate();}我在最高层的工作:
// i.e When the user clicks on a buttontry{ ...}catch(Exception ex){ ex.Log(); // Log exception -- OR -- ex.Log().Display(); // Log exception, then show it to the user with apologies...}我在一些所谓的函数中所做的事情:
// Calculation moduletry{ ...}catch(Exception ex){ // Add useful information to the exception throw new ApplicationException("Something wrong happened in the calculation module :", ex);}// IO moduletry{ ...}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 methodsinternal 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;}


