3

I am developing an ASP.NET web forms application. I have many functions that throw some exception on some particular situation. But there are a lot of functions. I don't want to remove and add throw ex; statement again and again when updating my application. So, is there any way I can check if the project is in debug mode? (i.e. to check if debug="true" in web.config).

try{
     //some code
}
catch (Exception ex)
{
     if(//----what condition to check debug mode?----)
         throw ex;
}
Aishwarya Shiva
  • 3,460
  • 15
  • 58
  • 107
  • 2
    Is this what you want? http://stackoverflow.com/questions/16357490/a-preferred-way-to-check-if-asp-net-web-application-is-in-debug-mode-during-runt – Equalsk Aug 07 '15 at 16:21
  • 7
    You should never do `throw ex` inside a catch block; this destroys the stack information. Just use `throw;` instead. – Erik Aug 07 '15 at 16:26

1 Answers1

7

You can use the #if compiler directive:

#if(DEBUG)
/// do your thing
#endif
helb
  • 7,609
  • 8
  • 36
  • 58
Aydin
  • 15,016
  • 4
  • 32
  • 42
  • 4
    An alternative is using the [Conditional("DEBUG")] attribute that you can set on a method that throws internally an exception. The compiler checks the conditional attribute and if you are NOT in debug mode, the method call is removed entierly from MSIL. – George Lica Aug 07 '15 at 17:32
  • 1
    @GeorgeLica definitely cleaner, though it should be kept in mind that it would apply to a whole method... You could have a method that takes an action delegate with that attribute applied. Would make things even more cleaner – Aydin Aug 07 '15 at 17:34
  • 1
    Very elegant! Very nice! That's why i love programming, it is like art: endless possibilities and endless styles to shape your code – George Lica Aug 08 '15 at 09:18