Have an unhandled exception crash the application

N

Nobody

In my C# application, I am creating a thread that is frequently doing stuff
and should be up for the life of the application. If an exception occurs, I
properly clean-up in finally blocks, but I never catch the exception...
because if an exception occurs it is a bug. So the thread terminates and an
UnhandledException event is invoked. In the data passed into the event,
there is a read-only IsTerminating property. For this property, MSDN says
"IsTerminating returns false for managed threads created by an application."
That is what is occuring my case for a release build.

I don't want my thread to just silently disappear, I want the application to
completely crash. I cannot modify IsTerminating to true, and rethrowing the
exception in the unhandled exception event has no effect. How can I get my
application to crash if my thread causes an unhandled exception?
 
D

Dave

Nobody said:
In my C# application, I am creating a thread that is frequently doing stuff
and should be up for the life of the application. If an exception occurs, I
properly clean-up in finally blocks, but I never catch the exception...
because if an exception occurs it is a bug. So the thread terminates and an
UnhandledException event is invoked. In the data passed into the event,
there is a read-only IsTerminating property. For this property, MSDN says
"IsTerminating returns false for managed threads created by an application."
That is what is occuring my case for a release build.

I don't want my thread to just silently disappear, I want the application to
completely crash. I cannot modify IsTerminating to true, and rethrowing the
exception in the unhandled exception event has no effect. How can I get my
application to crash if my thread causes an unhandled exception?
 
D

Dave

If you want the app to crash then don't catch the exception....let the
default unhandled exception handler get control. This will cause your app to
terminate.
 
N

Nobody

This is not true. If IsTerminating is false, the thread just dies, thats
it. Not specifying an unhandled exception does not change the behavior
(this is what I was initially doing, in fact).
 
T

Tian Min Huang

Hi,

Thanks for your post. As I understand, you want to exit your application
when it catches an exception in a thread. Please correct me if there is any
misunderstanding. I now share the following information with you:

1. I suggest that you can use Process.Kill method to stop the application.
Please refer to the following article for detailed information:

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/
frlrfsystemdiagnosticsprocessclasskilltopic.asp

2. According to MSDN documetion on IsTerminating property:

"This property returns true when an exception is received in, but not
handled by, an application's main thread. This property also returns true
if an unmanaged thread is executing managed code and receives an unhandled
exception. IsTerminating returns false for managed threads created by an
application."

Please kindly note that the exception thrown from your managed thread will
always have IsTerminating set to false. Depending on the type of your
project, you can post a message or by other means to let the main thread
throw an unhandled exception with IsTerminating equals to true.

Please feel free to let me know if you have any problems or concerns.

Have a nice day!

Regards,

HuangTM
Microsoft Online Partner Support
MCSE/MCSD

Get Secure! -- www.microsoft.com/security
This posting is provided "as is" with no warranties and confers no rights.
 
D

Dave

Nobody said:
This is not true. If IsTerminating is false, the thread just dies, thats
it. Not specifying an unhandled exception does not change the behavior
(this is what I was initially doing, in fact).

Interesting....I got the same results, which we definitely should NOT have
gotten. Here's the documentation for an unhandled exception...

"The UnhandledExceptionEventHandler delegate for this event provides default
handling for uncaught exceptions. When this event is not handled, the system
default handler reports the exception to the user and terminates the
application."

I consider the behavior we are seeing as a bug in the runtime....and a
serious one as it completely changes the effects. (I am curious if this was
introduced in v1.1 and that it worked correctly in v1.0.)
 
D

Dave

Hi,

According to the documentation....
"The UnhandledExceptionEventHandler delegate for this event provides default
handling for uncaught exceptions. When this event is not handled, the system
default handler reports the exception to the user and terminates the
application."

But that is not the behavior I am observing. I created a console app that
does *not* hook this event, and the app created a thread which threw an
exception, all that happens is the runtime prints out a diagnostic message
but the app does NOT terminate. It sat there in the main thread waiting for
the main thread to exit.

Is this a bug? It sure seems like it to me.

Dave
 
W

Willy Denoyette [MVP]

Dave said:
Hi,

According to the documentation....
"The UnhandledExceptionEventHandler delegate for this event provides default
handling for uncaught exceptions. When this event is not handled, the system
default handler reports the exception to the user and terminates the
application."

But that is not the behavior I am observing. I created a console app that
does *not* hook this event, and the app created a thread which threw an
exception, all that happens is the runtime prints out a diagnostic message
but the app does NOT terminate. It sat there in the main thread waiting for
the main thread to exit.

Is this a bug? It sure seems like it to me.

Dave
Dave,
Not sure how your's looks like, but this works for me.

using System;
using System.Threading;
namespace ConsoleApplication1
{
class Class1
{
public static void DoSomethingWrong()
{

int x=0,y=1;
Console.Write((y/x).ToString());
}
[STAThread]
static void Main(string[] args)
{
// AppDomain.CurrentDomain.UnhandledException += new
UnhandledExceptionEventHandler(StandardErrorHandler);
Thread t = new Thread(new ThreadStart(DoSomethingWrong));
t.Start();
}
static void StandardErrorHandler(object
sender,UnhandledExceptionEventArgs e)
{

Console.Write(e.ToString());
}
}
}


Willy.
 
N

Nobody

Couple things here:

1) Willy, you are just exiting the application right after you start the
thread. This creates a timing issue, perhaps a Join() call would help.

2) Willy, secondly, the code you provided never crashes for me. Be sure to
compile in RELEASE build and do NOT run it under Visual Studio. Navigate to
the build in Windows Explorer, double-click it, notice nothing will happen,
the application just starts and exits without crashing (even with a Join or
Sleep call).

3) Tian, not all applications are UI based, or can easily implement such
functionality into their source code. Basically you are saying that any
application that creates threads must make their main thread a UI-style
thread which listens for events (such as unhandled exceptions from other
threads). That is just ridiculous, its absolutely crazy that I cannot make
my application crash from an unhandled exception with little to no coding.
It should be the default behavior, in fact I consider it a bug otherwise.

Even scarier, P/Invoking DebugBreak() in the unhandled exception event has
no effect. This sucks.



Willy Denoyette said:
Dave said:
Hi,

According to the documentation....
"The UnhandledExceptionEventHandler delegate for this event provides default
handling for uncaught exceptions. When this event is not handled, the system
default handler reports the exception to the user and terminates the
application."

But that is not the behavior I am observing. I created a console app that
does *not* hook this event, and the app created a thread which threw an
exception, all that happens is the runtime prints out a diagnostic message
but the app does NOT terminate. It sat there in the main thread waiting for
the main thread to exit.

Is this a bug? It sure seems like it to me.

Dave
Dave,
Not sure how your's looks like, but this works for me.

using System;
using System.Threading;
namespace ConsoleApplication1
{
class Class1
{
public static void DoSomethingWrong()
{

int x=0,y=1;
Console.Write((y/x).ToString());
}
[STAThread]
static void Main(string[] args)
{
// AppDomain.CurrentDomain.UnhandledException += new
UnhandledExceptionEventHandler(StandardErrorHandler);
Thread t = new Thread(new ThreadStart(DoSomethingWrong));
t.Start();
}
static void StandardErrorHandler(object
sender,UnhandledExceptionEventArgs e)
{

Console.Write(e.ToString());
}
}
}


Willy.
 
D

Dave

Willy,

I had written something similar and had similar results. However, since
yesterday I've dug into this and I found out that this is actually the
expected (by design) behavior and the MSDN documentation is incomplete.

According to Richter's book on programming .NET, threadpool threads, manual
threads (such as the ones we've been starting), and the finalizer thread,
will all swallow unhandled exceptions. It's only the main thread of an app
and threads that wander in from unmanaged code that will cause the app to
crash when an unhandled exception occurs. It would have saved me a lot of
time and confusion if the MSDN docs clearly stated this.

I can understand their reasoning even though I disagree with it - I'd prefer
it if the behavior was consistent with all threads that started life in the
managed world.

Dave
 
D

Dave

According to Richter's book on programming .NET, threadpool threads, manual
threads (such as the ones we've been starting), and the finalizer thread,
will all swallow unhandled exceptions. It's only the main thread of an app
and threads that wander in from unmanaged code that will cause the app to
crash when an unhandled exception occurs.
3) Tian, not all applications are UI based, or can easily implement such
functionality into their source code. Basically you are saying that any
application that creates threads must make their main thread a UI-style
thread which listens for events (such as unhandled exceptions from other
threads). That is just ridiculous, its absolutely crazy that I cannot make
my application crash from an unhandled exception with little to no coding.
It should be the default behavior, in fact I consider it a bug otherwise.

It doesn't have to be a UI thread, just the main thread of the app.
According to what I learned you will need to do something similar to Tian's
suggestion about exiting the process manually if you want to ensure that all
unhandled exceptions cause the app to crash. Even throwing an exception
within the unhandled exception handler does not crash the app, so you will
need to use the Process.GetCurrentProcess().Kill call.

I'd prefer it if an UE caused the app to crash but there are arguments on
the other side that obviously the .NET team considered to be compelling.

Even scarier, P/Invoking DebugBreak() in the unhandled exception event has
no effect. This sucks.
Why use P/Invoke? (this may have side effects). Instead, try using
System.Diagnostics.Debugger.Break();
 
N

Nobody

So the question still is, with little to no programming how can I achieve
the (expected) behavior I am looking for? Please no "create a UI thread etc
etc" answers, that is useless to me.
 
W

Willy Denoyette [MVP]

Dave,
Exactly, I wasn't reading your reply correctly.
Indeed the behavior is by design, unhandled exceptions don't cross thread
boundaries, when they occur the running thread simply dies, but the calling
thread isn't affected.
But as you said, it's fairly easy to terminate the process, here is another
way to handle this.

// In your main thread

AppDomain.CurrentDomain.UnhandledException += new
UnhandledExceptionEventHandler(StandardErrorHandler);
.....
}
static void StandardErrorHandler(object
sender,UnhandledExceptionEventArgs e)
{
System.Environment.Exit(1);
}

But, it's not quite correct to say that all threadpool threads swallow
unhandled exception especially asynch delegates (using threadpool threads)
don't.

Compile following sample and watch....

using System;
using System.Threading;
public delegate void Proc(StateObject o);

public class StateObject {
int _Status = 0;
int State {
set { _Status = value;
}
get {
return _Status;
}
}
}
public class Forked {
static void Worker(StateObject o) {
// show that we are on a threadpool thread
Console.WriteLine("Thread {0}, executing Worker, " +
is {1}from the thread
pool.",Thread.CurrentThread.GetHashCode(),
Thread.CurrentThread.IsThreadPoolThread ? "" : "not ");
int r;
int y = 0;
r = 10/y;

public static void Main() {
Proc proc = new Proc(Worker);
StateObject s = new StateObject();
// Do some work using an async. delegate (running on a threadpool
thread)
IAsyncResult call = proc.BeginInvoke(s, null, null);
Console.WriteLine("Primary thread {0}",
Thread.CurrentThread.GetHashCode());
try {
//Just call EndInvoke at some point within a try block and you'll
see the exception.
proc.EndInvoke(call);
}
catch (Exception ex) {
Console.WriteLine("Error: {0}", ex.Message);
}
}
}



Dave said:
Willy,

I had written something similar and had similar results. However, since
yesterday I've dug into this and I found out that this is actually the
expected (by design) behavior and the MSDN documentation is incomplete.

According to Richter's book on programming .NET, threadpool threads, manual
threads (such as the ones we've been starting), and the finalizer thread,
will all swallow unhandled exceptions. It's only the main thread of an app
and threads that wander in from unmanaged code that will cause the app to
crash when an unhandled exception occurs. It would have saved me a lot of
time and confusion if the MSDN docs clearly stated this.

I can understand their reasoning even though I disagree with it - I'd prefer
it if the behavior was consistent with all threads that started life in the
managed world.

Dave
Dave,
Not sure how your's looks like, but this works for me.

using System;
using System.Threading;
namespace ConsoleApplication1
{
class Class1
{
public static void DoSomethingWrong()
{

int x=0,y=1;
Console.Write((y/x).ToString());
}
[STAThread]
static void Main(string[] args)
{
// AppDomain.CurrentDomain.UnhandledException += new
UnhandledExceptionEventHandler(StandardErrorHandler);
Thread t = new Thread(new ThreadStart(DoSomethingWrong));
t.Start();
}
static void StandardErrorHandler(object
sender,UnhandledExceptionEventArgs e)
{

Console.Write(e.ToString());
}
}
}


Willy.
 
D

Dave

You don't need a UI thread, just the main thread of your app. The console
app I tested this on is not a UI thread and it worked just fine. Just hook
the unhandled exception event and from within there call either
System.Diagnostics.Process.GetCurrentProcess().Kill(), or use
System.Environment.Exit(1).
 
N

Nobody

Though these methods get the application to exit, it still doesn't "crash"
the entire executable, and get the crash dialog. It's unfortunate that I
cannot P/Invoke DebugBreak() or something similar.
 
D

Dave

There are a number of articles written about exception handling in the CLR;
basically, the CLR installs default, low-level unhandled exception handlers
that provides the runtime with its default, backstop exception policy, and
crashing the application isn't it. No matter what you do in code, either
managed or unmanaged, that backstop will catch whatever you do.

What functionality are you trying to provide with this? You can already
exit; if you need notification or logging this is easy to provide. You might
want to take a look at the Exception Management blocks that Microsoft has
and use it.

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnbda/html/emab-rm.asp
 
T

Tian Min Huang

Hi,

Thanks for your feedback. I'd like to share the following information with
you:

There is no UI thread needed as described in my previous post. You can use
some synchronization objects (say, Event) to notify the main thread. Please
check the following code snippet and see if it is what you needed:

//-------------------------code snippet-----------------------------
using System;
using System.Threading;
namespace ConsoleApplication1
{
class Class1
{
static AutoResetEvent myResetEvent = new AutoResetEvent(false);

public static void MyThread()
{
try
{
throw new Exception("1");
}
catch (Exception e)
{
Console.WriteLine("Catch clause caught : " + e.Message);
myResetEvent.Set();
}
}
[STAThread]
static void Main(string[] args)
{
Thread myThread = new Thread(new ThreadStart(MyThread));
myThread.Start();

myResetEvent.WaitOne();
throw new Exception("1");
}
//-------------------------end of-------------------------

Hope this helps.

Regards,

HuangTM
Microsoft Online Partner Support
MCSE/MCSD

Get Secure! -- www.microsoft.com/security
This posting is provided "as is" with no warranties and confers no rights.
 
D

Dave

But, it's not quite correct to say that all threadpool threads swallow
unhandled exception especially asynch delegates (using threadpool threads)
don't.

Compile following sample and watch....
<snip>

Yeah I had forgotten all about that too. If an exception was thrown in the
async delegate callback then when you call EndInvoke it delivers the
exception (rethrows it) into the calling thread when EndInvoke is called.

Thanks for the reminder....there are so many finicky details and the
documentation for them is scattered in so many places it's hard to keep
track of it all.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top