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

来源:互联网 发布:软件测试教程 网盘 编辑:程序博客网 时间:2024/05/17 00:01
 

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

试题要求:

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

考察知识点:

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();

            }

        }

备注说明:

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

原创粉丝点击