Search code examples
c#asp.netexceptionvisual-studio-debugging

How does ASP.NET handle unhandled exceptions?


When writing for ASP.NET and, while the debugger is attached, if you visit a web page that throws an exception, the unhandled exception helper is launched at the line of code that caused the exception.

This occurs even if you only are catching unhandled exceptions and are not catching thrown exceptions. However, hitting F5, ignoring the exception, or not having the debugger attached does not cause the AppDomain to be torn down. Instead somehow ASP.NET handles the unhandled exception anyway.

How does this work, and can exception handling like this be implemented elsewhere so that other unhandled exceptions can be swallowed rather than kill the whole AppDomain or process?

Edit: To clarify, I understand how exception handling and try...catch blocks work. However, in this case it seems that the debugger is considering the exception unhandled while at the same time ASP.NET is wrapping the exception in a try...catch. That is the behavior I want to emulate.


Solution

  • How does this work,

    just wraps executing code in whatever exception-handling code they want. asp.net webpage (or view, or controller) is just a class, and how to use it is entirely up to host (in our case, asp.net).

    why does VS debugger break on it if it's handled?

    There's a quote from MSDN documentation:

    ASP.NET has a top-level exception handler that handles exceptions to show error pages to browser users. That top-level exception handler will stop an unhandled exception from breaking into the debugger unless Just My Code is turned on. Make sure that you enable Just My Code for ASP.NET debugging.

    Which means that if you have "Just my code" enabled in VS Debug options (and it's enabled by default) you'll break at exceptions that are unhandled in your own code, irregardless of whether they are handled in your caller or not.

    can exception handling like this be implemented elsewhere so that other unhandled exceptions can be swallowed rather than kill the whole AppDomain or process?

    You can't do that, it is a security measure.