Why is the exception in my delegate ignored?

J

james

When I compile and run this code outside of Visual Studio no exception
is reported to the console and the program continues to run.

class Program
{

static void Main(string[] args)
{
System.Timers.Timer t = new System.Timers.Timer(10);
t.Elapsed += delegate { throw new Exception("Kaboom"); };
t.Start();

Console.ReadLine();
}
}

Any ideas?

Thanks,
James
 
P

Peter Duniho

When I compile and run this code outside of Visual Studio no exception
is reported to the console and the program continues to run.

As far as I know, that's "by design". That is, since you have no
exception handler in the new thread, there's no code to detect the
exception and so the thread just exits (abnormally) without notice.

Pete
 
J

james

Thanks Pete. Along with that would anyone mind telling me the best
way to have that exception blow up my application? Is there a way
that would work with AppDomain.CurrDomain.UnhandledException?

Thanks,
James
 
J

Jon Skeet [C# MVP]

Peter Duniho said:
As far as I know, that's "by design". That is, since you have no
exception handler in the new thread, there's no code to detect the
exception and so the thread just exits (abnormally) without notice.

The fact that it's running from a timer is significant though. In .NET
2.0, if a new "plain" thread throws an exception, it will abort the
program. Try this:

using System;

class Program
{
static void Main(string[] args)
{

new System.Threading.Thread(Foo).Start();

Console.ReadLine();
}

static void Foo()
{
throw new Exception();
}
}

In .NET 1.1 (IIRC) this wouldn't stop the program, but in .NET 2.0 it
does. From a *very* quick bit of experimentation, it looks like
threadpool threads throwing exceptions doesn't cause the program to
terminate, and System.Timers.Timer runs on thread pool threads. That
could be an over-simplification though...
 
M

Michael Nemtsev

Hello James,

Yep, you can use this (or Application.ThreadException for winforms)
Take into account that not all unhandled exceptions in threads terminate
thread and shutdown hosting process - ThreadAbortException is out of this
fule, afaik

---
WBR, Michael Nemtsev [C# MVP].
My blog: http://spaces.live.com/laflour
Team blog: http://devkids.blogspot.com/

"The greatest danger for most of us is not that our aim is too high and we
miss it, but that it is too low and we reach it" (c) Michelangelo

J> Thanks Pete. Along with that would anyone mind telling me the best
J> way to have that exception blow up my application? Is there a way
J> that would work with AppDomain.CurrDomain.UnhandledException?
J>
J> Thanks,
J> James
 

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