Microsoft Knowledge Base Email Alertz

KBAlertz.com: Unhandled exceptions cause ASP.NET-based applications to unexpectedly quit in the .NET Framework 2.0

Receive Microsoft Knowledge Base articles by E-Mail?

Every night we scan the Microsoft Knowledge Base. If technologies you're interested in are updated, we'll send you an e-mail. You only get one e-mail a day, and only when new articles are added.

Click here to create a
FREE account
Already have an account?
[Click here to Login]

Search KbAlertz

Advanced Search

Webmasters
Put kbAlertz on your website.
[ Click Here for more! ]





ASP.NET 2.0 Web Hosting with SQL 2005: Click Here!
Discount ASP.NET Hosting


Bug Tracking Software
For bug tracking software or defect tracking software or issue tracking software, visit Axosoft.


Community Site



We Send hundreds of thousands of emails using ASP.NET Email



Expert Web Design & Graphic Design
Design44.com




Mentioned In








Microsoft Knowledge Base Article

This article contents is Microsoft Copyrighted material.
©2005-©2007 Microsoft Corporation. All rights reserved. Terms of Use | Trademarks




Unhandled exceptions cause ASP.NET-based applications to unexpectedly quit in the .NET Framework 2.0

Article ID:911816
Last Review:December 3, 2007
Revision:1.2
On This Page

SYMPTOMS

When an unhandled exception is thrown in a Microsoft ASP.NET-based application that is built on the Microsoft .NET Framework 2.0, the application unexpectedly quits. When this problem occurs, no exception information that you must have to understanding the issue is logged in the Application log.

However, an event message that is similar to the following may be logged in the System log:

Event Type: Warning
Event Source: W3SVC
Event Category: None
Event ID: 1009
Date: 9/28/2005
Time: 3:18:11
PM User: N/A
Computer: IIS-SERVER
Description:
A process serving application pool ‘DefaultAppPool’ terminated unexpectedly. The process id was ‘2548’. The process exit code was ‘0xe0434f4d’.

Additionally, an event message that is similar to the following may be logged in the Application log:

Event Type: Error
Event Source: .NET Runtime 2.0 Error Reporting
Event Category: None
Event ID: 5000
Date: 9/28/2005
Time: 3:18:02 PM
User: N/A
Computer: IIS-SERVER
Description:
EventType clr20r3, P1 w3wp.exe, P2 6.0.3790.1830, P3 42435be1, P4 app_web_7437ep-9, P5 0.0.0.0, P6 433b1670, P7 9, P8 a, P9 system.exception, P10 NIL.

Back to the top

CAUSE

This problem occurs because the default policy for unhandled exceptions has changed in the .NET Framework 2.0. By default, the policy for unhandled exceptions is to end the worker process.

In the Microsoft .NET Framework 1.1 and in the Microsoft .NET Framework 1.0, unhandled exceptions on managed threads were ignored. Unless you attached a debugger to catch the exception, you would not realize that anything was wrong.

ASP.NET uses the default policy for unhandled exceptions in the .NET Framework 2.0. When an unhandled exception is thrown, the ASP.NET-based application unexpectedly quits.

This behavior does not apply to exceptions that occur in the context of a request. These kinds of exceptions are still handled and wrapped by an HttpException object. Exceptions that occur in the context of a request do not cause the worker process to end. However, unhandled exceptions outside the context of a request, such as exceptions on a timer thread or in a callback function, cause the worker process to end.

Back to the top

RESOLUTION

To resolve this problem, use one of the following methods.

Back to the top

Method 1

Modify the source code for the IHttpModule object so that it will log exception information to the Application log. The information that is logged will include the following:
•The virtual directory path in which the exception occurred
•The exception name
•The message
•The stack trace
To modify the IHttpModule object, follow these steps.

Note This code will log a message that has the Event Type of Error and the Event Source of ASP.NET 2.0.50727.0 in the Application log. To test the module, request an ASP.NET page that uses the ThreadPool.QueueUserWorkItem method to call a method that throws an unhandled exception.
1.Put the following code in a file that is named UnhandledExceptionModule.cs.
using System;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Web;
 
namespace WebMonitor {
    public class UnhandledExceptionModule: IHttpModule {

        static int _unhandledExceptionCount = 0;

        static string _sourceName = null;
        static object _initLock = new object();
        static bool _initialized = false;

        public void Init(HttpApplication app) {

            // Do this one time for each AppDomain.
            if (!_initialized) {
                lock (_initLock) {
                    if (!_initialized) { 

                        string webenginePath = Path.Combine(RuntimeEnvironment.GetRuntimeDirectory(), "webengine.dll"); 

                        if (!File.Exists(webenginePath)) {
                            throw new Exception(String.Format(CultureInfo.InvariantCulture,
                                                              "Failed to locate webengine.dll at '{0}'.  This module requires .NET Framework 2.0.", 
                                                              webenginePath));
                        } 

                        FileVersionInfo ver = FileVersionInfo.GetVersionInfo(webenginePath);
                        _sourceName = string.Format(CultureInfo.InvariantCulture, "ASP.NET {0}.{1}.{2}.0",
                                                    ver.FileMajorPart, ver.FileMinorPart, ver.FileBuildPart);

                        if (!EventLog.SourceExists(_sourceName)) {
                            throw new Exception(String.Format(CultureInfo.InvariantCulture,
                                                              "There is no EventLog source named '{0}'. This module requires .NET Framework 2.0.", 
                                                              _sourceName));
                        }
 
                        AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(OnUnhandledException);
 
                        _initialized = true;
                    }
                }
            }
        }

        public void Dispose() {
        }

        void OnUnhandledException(object o, UnhandledExceptionEventArgs e) {
            // Let this occur one time for each AppDomain.
            if (Interlocked.Exchange(ref _unhandledExceptionCount, 1) != 0)
                return;

            StringBuilder message = new StringBuilder("\r\n\r\nUnhandledException logged by UnhandledExceptionModule.dll:\r\n\r\nappId=");

            string appId = (string) AppDomain.CurrentDomain.GetData(".appId");
            if (appId != null) {
                message.Append(appId);
            }
            

            Exception currentException = null;
            for (currentException = (Exception)e.ExceptionObject; currentException != null; currentException = currentException.InnerException) {
                message.AppendFormat("\r\n\r\ntype={0}\r\n\r\nmessage={1}\r\n\r\nstack=\r\n{2}\r\n\r\n",
                                     currentException.GetType().FullName, 
                                     currentException.Message,
                                     currentException.StackTrace);
            }           

            EventLog Log = new EventLog();
            Log.Source = _sourceName;
            Log.WriteEntry(message.ToString(), EventLogEntryType.Error);
        }

    }
}
2.Save the UnhandledExceptionModule.cs file to the following folder:
C:\Program Files\Microsoft Visual Studio 8\VC
3.Open the Microsoft Visual Studio 2005 Command Prompt.
4.Type sn.exe -k key.snk, and then press ENTER.
5.Type csc /t:library /r:system.web.dll,system.dll /keyfile:key.snk UnhandledExceptionModule.cs, and then press ENTER.
6.Type gacutil.exe /if UnhandledExceptionModule.dll, and then press ENTER.
7.Type ngen install UnhandledExceptionModule.dll, and then press ENTER.
8.Type gacutil /l UnhandledExceptionModule, and then press ENTER to display the strong name for the UnhandledExceptionModule file.
9.9. Add the following code to the Web.config file of your ASP.NET-based application.
<add name="UnhandledExceptionModule" 
	type="WebMonitor.UnhandledExceptionModule, <strong name>" />

Back to the top

Method 2

Change the unhandled exception policy back to the default behavior that occurs in the .NET Framework 1.1 and in the .NET Framework 1.0.

Note We do not recommend that you change the default behavior. If you ignore exceptions, the application may leak resources and abandon locks.

To enable this default behavior, add the following code to the Aspnet.config file that is located in the following folder:
%WINDIR%\Microsoft.NET\Framework\v2.0.50727
<configuration>
    <runtime>
        <legacyUnhandledExceptionPolicy enabled="true" />
    </runtime>
</configuration>

Back to the top

STATUS

This behavior is by design.

Back to the top

MORE INFORMATION

For more information about changes in the .NET Framework 2.0, visit the following Microsoft Developer Network (MSDN) Web site:
http://msdn2.microsoft.com/en-us/netframework/aa570326.aspx (http://msdn2.microsoft.com/en-us/netframework/aa570326.aspx)

Back to the top


APPLIES TO
•Microsoft .NET Framework 2.0

Back to the top

Keywords: 
kbtshoot kbfix kbprogramming kbprb KB911816

Back to the top

       

Community Feedback System

Very often, it takes hours to solve a problem. Very often, you've looked high and low, and have tried a lot of solutions. When you finally found it, chances are, it was because someone else helped you. Here's your chance to give back. Use our community feedback tool to let others know what worked for you and what didn't.

Please also understand that the community feedback system is not warranted to be correct, it's simply a system that we've built to let people try and help each other. If something in a feedback response doesn't make sense to you, or you're not comfortable making changes that the feedback talks about (like registry edits), please consult a professional.

Thank you for using kbAlertz.com Feedback System.

-- Scott Cate

Anonymous User Report As Irrelevant  
Written: 12/10/2005 1:38 AM
I'm missing a print mode for this page - or at least the link back to the genuine MS document which is a printer-friendly version.

JPortelas Report As Irrelevant  
Written: 2/21/2007 9:38 AM
I think this should be fixed on a SP instead of writting this code (even the solution is all in there). I don´t understand why, if I´m handling Application Errors in the Application_OnError event in the global.asax, the exception is still poping out of this... any hints? I think I will use method 2, but should not unhandled exceptions be garbage collected cause they are not referenced any more?

(Optional) Name

(Optional) Public URL Or Email

Comments
No HTML -- Text Only Please