473,404 Members | 2,213 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,404 software developers and data experts.

UnhandledException Handler

I have a simple C# Winforms application that has an UnhandledException
handler that writes to the log. This works fine if I throw a new exception
(like"bogus") but it does not gain control on a Zero Divide exception.

Is the UnhandledException handler supposed to receive control on all
exceptions or is the UnhandledException hander supposed to receive control
on all exceptions after all other exception handlers have "had a chance" to
service it?

Is the expected behavior that an UnhandledException handler will receive
Zero Divide exceptions or is the expected behavior that an Unhandled
Exception handler will never receive Zero Divide exceptions?

--
-- Thom Little -- www.tlaNET.net -- Thom Little Associates, Ltd.
--

Nov 15 '05 #1
4 2604
"Thom Little" <th**@tlanet.net> wrote:
I have a simple C# Winforms application that has an UnhandledException
handler that writes to the log. This works fine if I throw a new exception
(like"bogus") but it does not gain control on a Zero Divide exception.

Is the UnhandledException handler supposed to receive control on all
exceptions or is the UnhandledException hander supposed to receive control
on all exceptions after all other exception handlers have "had a chance" to
service it?

Is the expected behavior that an UnhandledException handler will receive
Zero Divide exceptions or is the expected behavior that an Unhandled
Exception handler will never receive Zero Divide exceptions?

--
-- Thom Little -- www.tlaNET.net -- Thom Little Associates, Ltd.


The UnhandledExceptionHandler never gets to see the "Attempted to divide by zero" because the exception IS being handled by the
"Application" class. The dialog box you see is a result of the System.Windows.Forms.NativeWindow.OnThreadExceptio n method
executing. A catch block in the Application.Run method is responsible for running it in response to encountering a
System.Exception-derived exception (this behaviour is disabled when the debugger is attached).

To override this behaviour, see a

http://msdn.microsoft.com/library/de...classtopic.asp

and code below.
Other problems related to that Exception Dialog can relate to the
<system.windows.forms jitDebugging="true" />

setting in the machine.config or app.config

http://msdn.microsoft.com/library/de...ndowsforms.asp
and to the setup of the HKEY_LOCAL_MACHINE\Software\Microsoft\.NETFramewor k\DbgJITDebugLaunchSetting Registry key
http://msdn.microsoft.com/library/de...hdebugging.asp
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Diagnostics;
using System.Threading;

namespace Unhandled {

public class UnhandledExceptionTest : System.Windows.Forms.Form {

private System.Windows.Forms.Button btnThrow;
private System.ComponentModel.Container components = null;

public UnhandledExceptionTest() {
InitializeComponent();
}

protected override void Dispose( bool disposing ) {
if( disposing ) {
if (components != null) {
components.Dispose();
}
}
base.Dispose( disposing );
}

#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.btnThrow = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// btnThrow
//
this.btnThrow.Location = new System.Drawing.Point(104, 24);
this.btnThrow.Name = "btnThrow";
this.btnThrow.TabIndex = 0;
this.btnThrow.Text = "&Throw";
this.btnThrow.Click += new System.EventHandler(this.btnThrow_Click);
//
// UnhandledExceptionTest
//
this.AutoScaleBaseSize = new System.Drawing.Size(6, 15);
this.ClientSize = new System.Drawing.Size(320, 65);
this.Controls.Add(this.btnThrow);
this.Name = "UnhandledExceptionTest";
this.Text = "UnhandledExceptionTest";
this.ResumeLayout(false);

}
#endregion

[STAThread]
static void Main() {

// Create AppDomain object
AppDomain adCurrent = AppDomain.CurrentDomain;

// Attach the UnhandledExceptionEventHandler to
// the UnhandledException of the APPDOMAIN object
adCurrent.UnhandledException += new UnhandledExceptionEventHandler(
UnhandledExceptionTest.UnhandledExceptionHandler
);

// Create an instance of the class with the methods
// that will handle the exception.
CustomExceptionHandler eh = new CustomExceptionHandler();

// Add the event handler to the APPLICATION object event.
// This will replace the default Exception dialog box
// shown by NativeWindow.OnThreadException
Application.ThreadException += new ThreadExceptionEventHandler(eh.OnThreadException);

Application.Run(new UnhandledExceptionTest());
}

// This will only catch unhandled exceptions NOT handled
// by System.Windows.Forms.NativeWindow.OnThreadExceptio n method.
private static void UnhandledExceptionHandler(
object sender,
UnhandledExceptionEventArgs ue
){
CustomExceptionHandler.Log.WriteEntry(
((Exception)ue.ExceptionObject).Message,
EventLogEntryType.Error
);
Application.Exit(); // Think twice before you just keep going
}

private void btnThrow_Click(object sender, System.EventArgs e) {
int a = 1;
int b = 10/(--a);
}

} // End class UnhandledExceptionTest

// Based on MSDN ThreadExceptionEventArgs Class code example
// Creates a class to handle the exception event.
internal class CustomExceptionHandler {
// Handles the exception event
public void OnThreadException(object sender, ThreadExceptionEventArgs t) {
//
// Do whatever needs to be done here
//
string errorMsg =
"An error occurred please contact the adminstrator "
+ "with the following information:\n\n"
+ t.Exception.Message
+ "\n\nStack Trace:\n"
+ t.Exception.StackTrace;

Log.WriteEntry( errorMsg, EventLogEntryType.Error );

Application.Exit(); // Think twice before you just keep going
}

private static EventLog eventLog_ = null;

private const string logName = "Application";
private const string sourceName = "UnhandledExceptionTest";
private const string machineName = ".";

public static EventLog Log {
get {
if (null != eventLog_) return eventLog_;

if( ! EventLog.SourceExists(sourceName, machineName) )
EventLog.CreateEventSource( sourceName, logName, machineName );

eventLog_ = new EventLog( logName, machineName, sourceName );
return eventLog_;
}
}
} // end class CustomExceptionHandler
} // end namespace Unhandled
Nov 15 '05 #2
It now makes sense.

Page 254 of the book "70-316, MCAD/MCSD Developing and Implementing
Windows-based Applications with Visual C# .NET and Visual Studio .NET
Training Guide" (Que) is apparently in error.

Reworking it with the information you provided produced the desired
results.

Thank you.

--
-- Thom Little -- www.tlaNET.net -- Thom Little Associates, Ltd.
--
Nov 15 '05 #3
"Thom Little" <th**@tlanet.net> wrote:
It now makes sense.

Page 254 of the book "70-316, MCAD/MCSD Developing and Implementing
Windows-based Applications with Visual C# .NET and Visual Studio .NET
Training Guide" (Que) is apparently in error.


Well, it could have been better. If you execute it with debug->Start everything seems to work fine as the Application.Run try block
is disabled; first you are notified when the exception occurs and if you select break and step through, the
UnhandledExceptionEventHandler will get the exception. Run the program with "Debug->Start Without Debugging" or create a release
version and the behaviour changes.

The UnhandledExceptionEventHandler should catch all of your exceptions, as your exceptions should be derived from
System.ApplicationException or one of its derived classes - I believe Application.Run will leave those alone
(it looks for System.SystemException and its descendents).
SystemExceptions should be handled at the site whenever possible, otherwise it is unlikely that you can recover from them.
But it seems that in windows forms you need to subscribe to both AppDomain.CurrentDomain.UnhandledException and
Application.ThreadException to perform application critical cleanup and logging.

I found this information in Jeffrey Richter's "Applied Microsoft .NET Framework Programming"
Chapter 18 "Exceptions" - "Unhandled Exceptions and Windows Forms"
Nov 15 '05 #4
Thank you AGAIN for even more helpful information.

F5 - Run with debugging - traps the exception
Ctrl-F5 - Run without debugging - does not trap the exception

--
-- Thom Little -- www.tlaNET.net -- Thom Little Associates, Ltd.
--

"UAError" <nu**@null.null> wrote in message
news:1c********************************@4ax.com...
"Thom Little" <th**@tlanet.net> wrote:
It now makes sense.

Page 254 of the book "70-316, MCAD/MCSD Developing and Implementing
Windows-based Applications with Visual C# .NET and Visual Studio .NET
Training Guide" (Que) is apparently in error.
Well, it could have been better. If you execute it with debug->Start

everything seems to work fine as the Application.Run try block is disabled; first you are notified when the exception occurs and if you select break and step through, the UnhandledExceptionEventHandler will get the exception. Run the program with "Debug->Start Without Debugging" or create a release version and the behaviour changes.

The UnhandledExceptionEventHandler should catch all of your exceptions, as your exceptions should be derived from System.ApplicationException or one of its derived classes - I believe Application.Run will leave those alone (it looks for System.SystemException and its descendents).
SystemExceptions should be handled at the site whenever possible, otherwise it is unlikely that you can recover from them. But it seems that in windows forms you need to subscribe to both AppDomain.CurrentDomain.UnhandledException and Application.ThreadException to perform application critical cleanup and logging.
I found this information in Jeffrey Richter's "Applied Microsoft .NET Framework Programming" Chapter 18 "Exceptions" - "Unhandled Exceptions and Windows Forms"

Nov 15 '05 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

7
by: Mike Strieder | last post by:
i want to catch all execeptions with my own handler, but the problem is, that the JIT-Debugger always start! i put also the <system.windows.forms jitDebugging="false" /> in the machine.config ...
2
by: Martin Lapierre | last post by:
How can I remove the default exception handler handler? When adding a custom handler, I can't get rid of the VS.NET unhandled exception dialog. Ex: AppDomain currentDomain =...
1
by: Kimmo Laine | last post by:
Hi, does the AppDomain.UnhandledException also work when you use it in Windows Service - i was unable to get the handler called when i generated an exception. thx Kimmo Laine
5
by: John Richardson | last post by:
Quick question about the UnhandledException event and associated Handler. I just implemented this handler for the first time, and am surprised that it this event is being raised for an exception...
2
by: guy | last post by:
In my application I have an event handler to catch unhandled exceptions, as per the MSDN documentation, however when an unhandled exception is thrown I get the Dialogue first, then the event...
4
by: Groundskeeper | last post by:
I can't seem to get a custom UnhandledException handler working for a Windows Service I'm writing in VB.NET. I've read the MSDN and tried various different placements of the AddHandler call, to no...
2
by: Chris Dunaway | last post by:
I am attempting to use the AppDomain.UnhandledException event in a Windows Forms app and also in a Windows Service. But the event doesn't seem to be called. In a Windows Forms app, the event IS...
7
by: Spam Catcher | last post by:
Hi all, When I'm debugging my application in VS.NET 2005, the debugger intercepts all unhandled exceptions and does not break into ApplicationEvents.UnhandledException. How do I debug...
1
by: =?Utf-8?B?QWxoYW1icmEgRWlkb3MgS2lxdWVuZXQ=?= | last post by:
Hi misters, is it possible use AppDomain.Currentdomain. UnhandledException event en ASP.NET 2.0 ?? I have this code: protected override void OnInit(EventArgs e) { base.OnInit(e);
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.