views:

382

answers:

4

I have a command line program in C# that I've wrapped with a try-catch block to keep it from crashing the console. However, while I am debugging it, if an exception is thrown somewhere in the DoStuff() method, Visual Studio will break on the "catch" statement. I want Visual Studio to break where the exception occurred. What's the best way to do this?

Comment out the try?
A setting in Visual Sudio?
An #if DEBUG statement?

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.
}
+4  A: 

I think setting VS to break on uncaught exceptions and wrapping the try/catch in ifdefs is how I would go about doing it.

tvanfosson
+8  A: 

You can turn on First chance exceptions in VS. This will allow you to be notified as soon as an exception is raised.

Paul Whitehurst
+1  A: 

There is an option to "Break on all exceptions". I'm not sure what version of VS you are using but in VS 2008 you can press Ctrl + D, E. You can then click the checkbox the Thrown checkbox for the types of exceptions you want to break on

I believe in previous versions of VS there was a Debug menu item to the effect of "Break on all exceptions". Unfortunately I don't have a previous version handy.

cangerer
+1  A: 

Here's how I do it for console tools running at continuous integration server:

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

Basically, in release mode we trap all unhandled exceptions, add them to the global exception counter, save to some file and then exit with error code.

In debug more exception goes right to the throwing spot, plus we use console logger by default to see what's happening.

PS: ExceptionCounters, ConsoleLog etc come from the Lokad Shared Libraries

Rinat Abdullin