zoukankan      html  css  js  c++  java
  • C#程序在某个方法执行出错,打印当前执行方法名称,便于排查错误!

    using System;
    using System.Diagnostics;
    using ConsoleExtClass;
    
    namespace WhenErrorPrintExecuteMethod
    {
        /// <summary>
        ///     https://www.cnblogs.com/LifeDecidesHappiness/p/15638935.html
        ///     C#程序在某个方法执行出错,打印当前执行方法名称,便于排查错误!
        ///     LDH @ 2021-12-3
        /// </summary>
        internal class Program
        {
            private static void Main()
            {
                Console.Title = "C#程序在某个方法执行出错,打印当前执行方法名称,便于排查错误!";
    
                WhenDivideByZeroExceptionOccurs();
    
                Console.ReadKey();
            }
    
            /// <summary>
            ///     当程序执行有错误时候,抛出异常,并打印出所在方法名称,便于排查
            /// </summary>
            private static void WhenDivideByZeroExceptionOccurs()
            {
                // 获取执行方法名称
                var method = new StackTrace().GetFrame(0).GetMethod();
    
                try
                {
                    var a = 5;
                    var b = 0;
                    var c = a / b;
                    Console.WriteLine("Result:" + c);
                }
                catch (Exception ex)
                {
                    PrintLine();
                    var info = $"出现错误的方法名:{method.Name},{Environment.NewLine}具体错误如下:{Environment.NewLine}{ex.Message}";
                    Console.WriteLine(info);
    
                    PrintLine();
                    ConsoleExt.ErrorLine(info, true);
    
                    PrintLine();
                }
            }
    
            private static void PrintLine()
            {
                Console.WriteLine("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━");
            }
        }
    }

     

    本文作者:Love In Winter
    本文链接:https://www.cnblogs.com/LifeDecidesHappiness/p/15638935.html
    版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!
    声援博主:如果您觉得文章对您有帮助,可以扫一扫,任意打赏,您的鼓励是博主的最大动力!
    扫一扫,支付宝打赏 扫一扫,微信打赏
  • 相关阅读:
    Python 线程(三):Condition(条件变量)
    Python 线程(二):简单锁实现线程同步
    Python 线程(一):创建线程
    Python 正则表达式
    Python List 、 元组、字典操作
    Python 特殊函数(filter, map, reduce等)
    (一) log4cpp的安装
    (六) 字符和字符串
    (五) 使用DLL函数
    (四) 自定义函数
  • 原文地址:https://www.cnblogs.com/LifeDecidesHappiness/p/15638935.html
Copyright © 2011-2022 走看看