如何将程序中捕获的异常信息写到文本文件中

 

我们在软件开发过程中,或软件运行时常常会遇到系统引发了异常,而我们修复该功能时最有价值的资料莫过于异常信息了。那么我们如何将系统引发的异常写到文本文件中,供我们利用呢?

试题要求:

如何将程序中捕获的异常信息写到文本文件

考察知识点:

Exception知识点、I/O流相关的知识

参考答案:

private static void CatchSystemException()

        {

            try

            {

                int a = 9;

                int b = 0;

                int c = a / b;

            }

            catch (Exception ex)

            {

                string errorInfos = ex.Message + Environment.NewLine;

                errorInfos += ex.Source + Environment.NewLine;

                errorInfos += ex.StackTrace + Environment.NewLine;

                errorInfos += ex.TargetSite.Name + Environment.NewLine;

                string filePath = Path.Combine(Environment.CurrentDirectory, "error.txt");

                //*********************接下来用三种方式去写文件********************

                //通过字节流

                Stream fs = new FileStream(filePath, FileMode.Create);

                byte[] data=System.Text.Encoding.Default.GetBytes(errorInfos);

                fs.Write(data, 0, data.Length);

                fs.Flush();

                fs.Close();

                //通过字符流

                StreamWriter streamWriter = new StreamWriter(filePath, true,Encoding.Default);

                streamWriter.WriteLine(errorInfos);

                streamWriter.Flush();

                streamWriter.Close();

                //通过静态类File去创建文件,然后再通过字符流写文件

                FileStream fileStream;

                TextWriter writer;

                if (!File.Exists(filePath))

                {

                    fileStream = File.Create(filePath);

                    writer = new StreamWriter(fileStream);

                }

                else

                {

                    writer = new StreamWriter(filePath);

                }

                writer.WriteLine(errorInfos);

                writer.Flush();

                writer.Close();

            }

        }

备注说明:

如果系统中处处这样去捕获异常,对程序员来讲工作量就太大了,那么该如何把异常信息写到合适的位置来把程序员从该工作中解放出来呢?有兴趣的可以想象办法。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值