Reputation: 20708
When I want to debug my application that throws exception, that means I need to disable the try-catch block like this:
#if !DEBUG
try
{
#endif
// Do something
#if !DEBUG
}
catch (ArgumentException)
{
Console.WriteLine("Something wrong");
}
#endif
Note: I know about break on handled exception of Visual Studio, but the downside is it break at every exception of the same type. EDIT to rephrase my meaning: For example, function A and B both throws NullReferenceException, but I only want to check when A throws it, but not B (handled NulRefExc in B is already correct).
One may ask why I need that. Usually I run ASP.NET MVC code without Debugging (but still in Debug build, which has DEBUG variable), and throwing exception is really great instead of catching it (in dev mode only, of course), because the error page with stack trace will be shown, so we can track the error much quicker.
Is there any cleaner way to write the upper code?
Upvotes: 6
Views: 2525
Reputation: 9650
Since C# 6 you also may use exception filters for that:
try
{
// Do something
}
catch (ArgumentException) when (!Env.Debugging)
{
// Handle the exception
}
Having Env.Debugging
defined somewhere as
public static class Env
{
#if DEBUG
public static readonly bool Debugging = true;
#else
public static readonly bool Debugging = false;
#endif
}
As an additional bonus you'll get original call stack in the exception object when it is not caught (due to when
test failed, i.e. in debug). With a re-thrown exception you would have to provide the original exception as the inner one and make some extra effort to deal with it.
This approach also allows to enable/disable exception handling based on other condition, a web.config
setting for example, which would allow you to swicth without recompilation:
public static class Env
{
public static readonly bool Debugging =
Convert.ToBoolean(WebConfigurationManager.AppSettings["Debugging"]);
}
Upvotes: 13
Reputation: 27039
Two things:
#if DEBUG
? Console.WriteLine
is meaningless in ASP.NET. See this for more.What you should be doing is logging the error to either a database, a file or something. This will avoid all the #if DEBUG
s all over the code. Please see this for more on logging.
This has additional benefits:
Upvotes: 1
Reputation: 764
just an idea leave the try catch
then do
catch (ArgumentException)
{
#if DEBUG
throw SomeCustomExceptionYouCatchWith_break_on_handled_exception();
#endif
Console.WriteLine("Something wrong");
}
Upvotes: 3