【问题标题】:Ignoring try block in C# command line program忽略 C# 命令行程序中的 try 块
【发布时间】:2009-01-08 03:05:47
【问题描述】:

我有一个 C# 命令行程序,我用 try-catch 块包装了它,以防止它崩溃控制台。但是,当我调试它时,如果在 DoStuff() 方法的某处抛出异常,Visual Studio 将在“catch”语句上中断。我希望 Visual Studio 中断发生异常的位置。最好的方法是什么?

注释掉试试?
Visual Sudio 中的设置?
#if DEBUG 语句?

static void Main(string[] args)
{
    try
    {
        DoStuff();
    }
    catch (Exception e)
    {  //right now I have a breakpoint here
        Console.WriteLine(e.Message);
    }
}

private void DoStuff()
{
    //I'd like VS to break here if an exception is thrown here.
}

【问题讨论】:

    标签: c# visual-studio-2008 command-line console


    【解决方案1】:

    你可以在VS中开启First chance exceptions。这将允许您在引发异常时立即收到通知。

    【讨论】:

      【解决方案2】:

      我认为将 VS 设置为 break on uncaught exceptions 并将 try/catch 包装在 ifdefs 中是我将要做的事情。

      【讨论】:

        【解决方案3】:

        有一个选项可以“中断所有例外”。我不确定您使用的是哪个版本的 VS,但在 VS 2008 中,您可以按 Ctrl + D、E。然后您可以单击复选框“抛出”复选框,了解您想要中断的异常类型

        我相信在以前的 VS 版本中,有一个 Debug 菜单项的效果是“中断所有异常”。不幸的是,我手头没有以前的版本。

        【讨论】:

          【解决方案4】:

          对于在持续集成服务器上运行的控制台工具,我是这样做的:

          private static void Main(string[] args)
          {
            var parameters = CommandLineUtil.ParseCommandString(args);
          
          #if DEBUG
            RunInDebugMode(parameters);
          #else
            RunInReleaseMode(parameters);
          #endif
          }
          
          
          static void RunInDebugMode(IDictionary<string,string> args)
          {
            var counter = new ExceptionCounters();
            SetupDebugParameters(args);
            RunContainer(args, counter, ConsoleLog.Instance);
          }
          
          static void RunInReleaseMode(IDictionary<string,string> args)
          {
            var counter = new ExceptionCounters();
            try
            {
              RunContainer(args, counter, NullLog.Instance);
            }
            catch (Exception ex)
            {
              var exception = new InvalidOperationException("Unhandled exception", ex);
              counter.Add(exception);
              Environment.ExitCode = 1;
            }
            finally
            {
              SaveExceptionLog(parameters, counter);
            }
          }
          

          基本上,在释放模式下,我们捕获所有未处理的异常,将它们添加到全局异常计数器,保存到某个文件,然后退出并返回错误代码。

          在调试中,更多异常直接出现在抛出点,此外,我们默认使用控制台记录器来查看发生了什么。

          PS:ExceptionCounters、ConsoleLog等来自Lokad Shared Libraries

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2021-09-09
            • 2023-03-13
            • 2014-12-06
            • 1970-01-01
            • 1970-01-01
            • 2023-04-01
            • 1970-01-01
            相关资源
            最近更新 更多