一个简单的统一异常处理方法。系统底层出现异常,写入记录文件,系统顶层捕获底层异常,显示提示信息。
/// <summary> /// 自定义异常类 /// </summary> public static class exceptionextension { /// <summary> /// 用户自定义错误消息 /// </summary> public static string errormessage { get; t; } /// <summary> /// 写入异常日志 /// </summary> /// <param name="ex"></param> /// <param name="message">用户自定义错误消息</param> public static void writerexceptionlog(exception ex, string message = "") { string filepath = environment.currentdirectory.replace(@"\bin\debug", "") + @"\errorlog"; if (!system.io.directory.exists(filepath)) { system.io.directory福建集美大学.createdirectory(filepath); } string filename = filepath + @"\errorlog.txt"; stringbuilder errorinfo = new stringbuilder(); errorinfo.append($"*******异常发生时间:{datetime.now}*******\n"); errorinfo.appendformat(" 异常类型: {0} \n", ex.hresult); //msg.appendformat(" 导致当前异常的 exception 实例: {0} \n", ex.innerexception); errorinfo.appendformat(" 导致异常的应用程序或对象的名称: {0} \n", ex.source); errorinfo.appendformat(" 解牛斫轮引发异常的方法: {0} \n", ex.targetsite); errorinfo.appendformat(" 异常堆栈信息: {0} \n", ex.stacktrace); errorinfo.appendfo百家讲坛李清照rmat(" 异常消息: {0} \n", ex.message); errori悄然无息nfo.appendformat(" 系统信息: {0} \n", message); errormessage += message; try { if (file.exists(filename)) { using (streamwriter tw = file.appendtext(filename)) { tw.writeline(errorinfo.tostring()); } } el { textwriter tw = new streamwriter(filename); tw.writeline(errorinfo.tostring()); tw.flush();//将缓冲区的数据强制输出,清空缓冲区 tw.clo();//关闭数据流 tw = null; } } catch (exception) { console.readkey(); } } }}
比较简单,该类仅定义了一个属性和一个方法。具体使用如下:系统底层(例如数据访问层或业务逻辑层)发现异常时, 记录异常信息,将异常上抛。例如:
//后台处理try{ //有可能发生异常操作}catch (exception ex){ string strslq = ""; exceptionextension.writerexceptionlog(ex, "在查询记录时发生异常。sql语句为:" + strslq); throw;//向上抛出异常}finally{ //清理}杭州商场
用户交互层,捕获底层异常,显示提示信息。例如:
//用户界面 try { //调用底层有可能发生异常操作 } catch (exception) { //messagebox.show(exceptionextension.errormessage, "系统异常错误", messageboxbuttons.ok, messageboxicon.error); } finally { //清理 }
到此这篇关于c# winform自定义异常处理方法的文章就介绍到这了,更多相关c# winform异常处理方法内容请搜索www.887551.com以前的文章或继续浏览下面的相关文章希望大家以后多多支持www.887551.com!
本文发布于:2023-04-04 12:52:51,感谢您对本站的认可!
本文链接:https://www.wtabcd.cn/fanwen/zuowen/a333a504462205878042352f9e0d426f.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文word下载地址:C# WINFORM自定义异常处理方法.doc
本文 PDF 下载地址:C# WINFORM自定义异常处理方法.pdf
留言与评论(共有 0 条评论) |