2009-01-08 59 views
3

我在C#中有一個命令行程序,我用try-catch塊包裝它以防止崩潰控制檯。然而,當我調試它時,如果在DoStuff()方法的某個地方拋出一個異常,Visual Studio將打破「catch」語句。我想讓Visual Studio打破出現異常的位置。什麼是最好的方法來做到這一點?忽略C#命令行程序中的try塊

評論試試?
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. 
} 

回答

1

有一個選項可以「打破所有例外」。我不確定您使用的VS版本是什麼,但在VS 2008中,您可以按Ctrl + D,E。然後,您可以單擊Thrown複選框以選擇想要打破的異常類型

我相信在以前版本的VS中,有一個Debug菜單項,其效果是「打破所有異常」。不幸的是,我沒有以前的版本,方便。

1

這裏是我如何做到這一點的控制檯工具,在持續集成服務器上運行:

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

基本上,在發行模式中,我們捕獲所有未處理的異常,將它們添加到全局異常計數器,保存一些文件,然後退出時顯示錯誤代碼。

在調試中,更多的異常直接進入投擲點,另外我們默認使用console logger來查看發生了什麼。

PS:ExceptionCounters,ConsoleLog等來自Lokad Shared Libraries