473,769 Members | 6,305 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Exception Handling Question

I'm implementing a centralized exception handling routine using the
Enterprise Library Exception Management Application Block.

I trap all unhandled exceptions to one place using the following method:

// --- Create an Exception Handler for Thread Exceptions ----------------

Application.Thr eadException += new
ThreadException EventHandler(On ThreadException );

// --- Create an Exception Handler for Unhandled Exceptions -------------

AppDomain currentDomain = AppDomain.Curre ntDomain;

currentDomain.U nhandledExcepti on += new
UnhandledExcept ionEventHandler (OnUnhandledExc eption);

private static void OnThreadExcepti on(object sender,

ThreadException EventArgs t)

//
*************** *************** *************** *************** *************** ***

// Handles Normal Thread Exceptions

//
*************** *************** *************** *************** *************** ***

{

Exceptions.LogA ndReportError(t .Exception);

}

private static void OnUnhandledExce ption(object sender,

UnhandledExcept ionEventArgs args)

//
*************** *************** *************** *************** *************** ***

// Handles All Unhandled Exceptions

//
*************** *************** *************** *************** *************** ***

{

Exceptions.LogA ndReportError(a rgs.ExceptionOb ject as System.Exceptio n);

}

The problem I have is that exceptions that occur on a background thread are
not being picked up. If I do a "throw" on an exception in a background
thread it has no place to go and just disappears as an unhandled exception.
How can I pick up these exceptions without handling them in the background
thread?

Thanks,

Chuck Cobb
Apr 21 '06
16 2546
Thanks...
"Willy Denoyette [MVP]" <wi************ *@telenet.be> wrote in message
news:OP******** ******@TK2MSFTN GP04.phx.gbl...

"Chuck Cobb" <ch********@oxf ordcorp.com> wrote in message
news:%2******** ********@TK2MSF TNGP03.phx.gbl. ..
| Thanks for posting this code I tried it out and the primary difference
| between your code and my code is how it starts an auxiliary thread:
|
| Your code:
| new Thread(delegate ()
|
| {
|
| ThrowExceptionI nsideTryCatch() ;
|
| }).Start();
|
| My Code:
|
| MethodInvoker mi = new
MethodInvoker(T hrowExceptionOu tsideTryCatch);
|
| mi.BeginInvoke( null, null);
|

This doesn't start a auxiliary thread, it delegates the
ThrowExceptionO utsideTryCatch function to execute on the 'UI thread', but
as
you call this from the UI thread, it simply boils down into a simple call
to
ThrowExceptionO utsideTryCatch.

Willy.

Apr 22 '06 #11
Thanks. First, I could indeed reproduce the problem.

But as Willy already said, just calling some variant of Invoke usually
doesn't start a background thread at all -- it merely performs an
invocation on the current thread, same as just writing out the method
call. That's true even for BeginInvoke/EndInvoke (on the Control
class) which only perform cross-thread marshalling if needed.

Nevertheless, the UnhandledExcept ion handler should be triggered. But
this is apparently one of the undocumented features of the
undocumented MethodInvoker.B eginInvoke method that you were using. How
do you know it's undocumented and should not be used? Because this
method does not appear in the MSDN docs, and its IntelliSense display
does not show any description other than the prototype.

In fact, MethodInvoker offers only a single "official" invocation
method, and that's DynamicInvoke (inherited from its base class
Delegate). And when I used that documented method the
UnhandledExcept ion handler was properly triggered -- for either
ThrowException. .. method, whichever is executed first.

Moral: Don't use undocumented .NET Framework methods! Actually, don't
use MethodInvoker at all. It's just a simple delegate, and the three
methods it offers in addition to Delegate/MulticastDelega te are all
intended for internal Windows.Forms use only. The class should never
have been publically exposed in the first place IMO.
--
http://www.kynosarges.de
Apr 22 '06 #12
Christoph,

See inline..

Willy.

"Christoph Nahr" <ch************ @kynosarges.de> wrote in message
news:1u******** *************** *********@4ax.c om...
| Thanks. First, I could indeed reproduce the problem.
|
| But as Willy already said, just calling some variant of Invoke usually
| doesn't start a background thread at all -- it merely performs an
| invocation on the current thread, same as just writing out the method
| call. That's true even for BeginInvoke/EndInvoke (on the Control
| class) which only perform cross-thread marshalling if needed.
|
| Nevertheless, the UnhandledExcept ion handler should be triggered.

No it should not, the exception is thrown on the UI thead, so the
ThreadException handler is invoked.
UnhandledExcept ion handlers are only invoked when "unhandled" exceptions are
originating from non UI threads.
But
| this is apparently one of the undocumented features of the
| undocumented MethodInvoker.B eginInvoke method that you were using. How
| do you know it's undocumented and should not be used? Because this
| method does not appear in the MSDN docs, and its IntelliSense display
| does not show any description other than the prototype.
|
| In fact, MethodInvoker offers only a single "official" invocation
| method, and that's DynamicInvoke (inherited from its base class
| Delegate). And when I used that documented method the
| UnhandledExcept ion handler was properly triggered -- for either
| ThrowException. .. method, whichever is executed first.
|
| Moral: Don't use undocumented .NET Framework methods! Actually, don't
| use MethodInvoker at all. It's just a simple delegate, and the three
| methods it offers in addition to Delegate/MulticastDelega te are all
| intended for internal Windows.Forms use only. The class should never
| have been publically exposed in the first place IMO.
| --
| http://www.kynosarges.de
Apr 22 '06 #13
On Sat, 22 Apr 2006 11:23:45 +0200, "Willy Denoyette [MVP]"
<wi************ *@telenet.be> wrote:
No it should not, the exception is thrown on the UI thead, so the
ThreadExceptio n handler is invoked.
UnhandledExcep tion handlers are only invoked when "unhandled" exceptions are
originating from non UI threads.


Willy, haven't you read the rest of my post? The UnhandledExcept ion
handler *was* triggered when BeginInvoke was changed to DynamicInvoke,
or when the exception methods were called directly. The
ThreadException handler *was not* triggered.

As to why, I'm not sure. In the test program the exception is thrown
before a form is even constructed, so technically there is no GUI
(Windows Forms) thread at the time of the exception. Remember that
ThreadException is a Windows Forms feature, not a general threading
feature. Possibly it requires a window event queue to work.
--
http://www.kynosarges.de
Apr 22 '06 #14
Oh dear, oh dear. Attention: I'm a dumbass. Willy is also a dumbass.
Chuck is very smart and was actually mostly right. Should have read
the chapter on asynchronous operations in Jeff Richter's "CLR via C#"
before replying. I'm very sorry... here comes the correct version.

I got completely sidetracked by reminiscences of Control.BeginIn voke
which does not start a new thread. But in fact, the MethodInvoker
methods Invoke/BeginInvoke/EndInvoke are undocumented because they're
*auto-generated* for each delegate class. The BeginInvoke method is
proper to call and does, in fact, start a new background thread.

I no longer understand why the MSDN docs say that MethodInvoker.I nvoke
is "for internal use" only; that does not seem to make sense. All of
these methods should be proper for anyone's use.

Okay. So why didn't UnhandledExcept ion get called? That's because
the auto-generated BeginInvoke method of a delegate executes on a
thread in the CLR thread pool, and any exceptions thrown by a thread
pool thread are automatically swallowed by the CLR until the
corresponding EndInvoke is called, at which point they're thrown.

So Chuck should see his UnhandledExcept ion handler activated when the
BeginInvoke call is paired with an EndInvoke call.

All this is explained in Jeff Richter's "CLR via C#", chapter 23,
pages 614f. Ironically, it's the book I tell everyone to read... that
was the last chapter I had not gotten around to read until now.
--
http://www.kynosarges.de
Apr 22 '06 #15
On Sat, 22 Apr 2006 14:10:20 +0200, Christoph Nahr
<ch************ @kynosarges.de> wrote:
I no longer understand why the MSDN docs say that MethodInvoker.I nvoke
is "for internal use" only; that does not seem to make sense. All of
these methods should be proper for anyone's use.


Jesus, what's wrong with me? The MSDN docs don't say that at all,
that was some other method I was looking up. Scratch that paragraph.
--
http://www.kynosarges.de
Apr 22 '06 #16
Well, actually I didn't pay attention to the BeginIvoke call (I even didn't
look at the attached code), I only noticed the MethodInvoker, which was
enough to conclude that the exception was not thrown on an "auxiliary"
thread (but being a dumbass, I wrongly assumed that it was on the UI
thread). Notice that I call an "auxiliary thread", a thread that is
explicitly created via a call to a Thread class constructor. Only unhandled
exceptions originating from "auxiliary" threads are routed to the
UnhandledExcept ion handler, 'unhandled' exceptions originating from pool
threads are not, they have to be handled explicitly, as you correctly
mentioned. Note that every BeginInvoke on a delegate has to be paired with
an EndInvoke call, this is mandatory on the CLR, failing to do this may
result in handle leaks.

Willy.

"Christoph Nahr" <ch************ @kynosarges.de> wrote in message
news:hr******** *************** *********@4ax.c om...
| Oh dear, oh dear. Attention: I'm a dumbass. Willy is also a dumbass.
| Chuck is very smart and was actually mostly right. Should have read
| the chapter on asynchronous operations in Jeff Richter's "CLR via C#"
| before replying. I'm very sorry... here comes the correct version.
|
| I got completely sidetracked by reminiscences of Control.BeginIn voke
| which does not start a new thread. But in fact, the MethodInvoker
| methods Invoke/BeginInvoke/EndInvoke are undocumented because they're
| *auto-generated* for each delegate class. The BeginInvoke method is
| proper to call and does, in fact, start a new background thread.
|
| I no longer understand why the MSDN docs say that MethodInvoker.I nvoke
| is "for internal use" only; that does not seem to make sense. All of
| these methods should be proper for anyone's use.
|
| Okay. So why didn't UnhandledExcept ion get called? That's because
| the auto-generated BeginInvoke method of a delegate executes on a
| thread in the CLR thread pool, and any exceptions thrown by a thread
| pool thread are automatically swallowed by the CLR until the
| corresponding EndInvoke is called, at which point they're thrown.
|
| So Chuck should see his UnhandledExcept ion handler activated when the
| BeginInvoke call is paired with an EndInvoke call.
|
| All this is explained in Jeff Richter's "CLR via C#", chapter 23,
| pages 614f. Ironically, it's the book I tell everyone to read... that
| was the last chapter I had not gotten around to read until now.
| --
| http://www.kynosarges.de
Apr 23 '06 #17

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

Similar topics

11
2886
by: adi | last post by:
Dear all, This is more like a theoretical or conceptual question: which is better, using exception or return code for a .NET component? I had created a COM object (using VB6), which uses return code (not generating error/exception) so it is more compatible with other programming language.
44
4228
by: craig | last post by:
I am wondering if there are some best practices for determining a strategy for using try/catch blocks within an application. My current thoughts are: 1. The code the initiates any high-level user tasks should always be included in a try/catch block that actually handles any exceptions that occur (log the exception, display a message box, etc.). 2. Low-level operations that are used to carry out the high level tasks
3
1634
by: dhussong | last post by:
I'm trying to implement a generic exception handling routine that will write information to a text file at the time the exception occurred. I am using the Microsoft Application Block for Exception Handling to write to a text file. This is working great plus I get the call stack which is an added bonus. What I really want to get is the value of parameters and variables in each method in the call stack at the time of the exception. I know I...
3
3211
by: Larry Herbinaux | last post by:
I have built an asychronous TCP Server that uses the thread pool. I have two levels of exception handling in case the handling of the inner catch block throws an exception. The outer catch block does nothing put print a string literal to our logging mechanism. The general structure for this is: AsyncReceiveCallback { try { OnReceiveDelegate();
5
3831
by: Bry | last post by:
I've created a class that offers an enhanced way of handling fatal exceptions. The class allows the user to optionaly submit a http based anonymous error report to myself, and also records details in the application log. The static method is overloaded, and supports passing exceptions and/or strings just like throwing an exception.The class will also fall back to the standard exception handling if something goes wrong in my class. As an...
14
2111
by: jehugaleahsa | last post by:
Hello: As an avid reader of C++ books, I know a lot of programmers out there are confronted with the challenge of exception safety. For those who don't know what it is, it is writing code in such a way that an exception will not cause a class to be left in an unstable state. For instance, you wouldn't want an OutOfMemoryException leaving a container with an invalid size or missing elements.
2
4047
by: jayapal | last post by:
Hi , I am using the NEW operator to allocate the memory in many places of my code.But I am not doing any error hadling or exception handling.Can any one suggests me how to do exception handling, which code part I have to add to do the exception handling Thanks in advance, ..
1
3109
by: George2 | last post by:
Hello everyone, Such code segment is used to check whether function call or exception- handling mechanism runs out of memory first (written by Bjarne), void perverted() { try{
35
3512
by: eliben | last post by:
Python provides a quite good and feature-complete exception handling mechanism for its programmers. This is good. But exceptions, like any complex construct, are difficult to use correctly, especially as programs get large. Most of the issues of exceptions are not specific to Python, but I sometimes feel that Python makes them more acute because of the free-n- easy manner in which it employs exceptions for its own uses and allows users...
9
1931
by: =?Utf-8?B?UmFq?= | last post by:
How do I know which methods will throw exception when I am using FCL or other third party .Net library? I am developer of mostly native Windows applications and now .Net. After working few months in Java, I am thinking why Win32 APIs or even .Net documentation not clear on which methods will throw exception or what exceptions can be expected. Jave APIs clearly define exceptions that can be expected and enforces that we handle them. ...
0
9587
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10045
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9993
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8870
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6672
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5298
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5447
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3561
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2815
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.