Reputation: 1961
Let's assume I have following console application:
Thread thread = new Thread(new ThreadStart(() => { throw new Exception(); }));
thread.IsBackground = true;
thread.Start();
while (true)
Console.WriteLine("Hello from main thread");
Is it possible to make entire application not crashing because of background tread's exception (without using try..catch of course)?
Upvotes: 2
Views: 5383
Reputation: 29
Using a Task instead does not crash the application
Task.Factory.StartNew(() => { throw new Exception(); });
while (true) Console.WriteLine("Hello from main thread");
Upvotes: -1
Reputation: 1289
Attach your unhandled exceptions handler: http://msdn.microsoft.com/en-us/library/system.appdomain.unhandledexception.aspx
The better way you can achieve desired result (Ok, with try/catch, but only once) with global handler:
public static void GlobalHandler(ThreadStart threadStartTarget)
{
try
{
threadStartTarget.Invoke();
}
catch (Exception ex)
{
//handle exception here
}
}
And then start your threads:
Thread thread = new Thread(o => GlobalHandler(ThreadMethod));
thread.Start();
P.S. However, really, I don't like idea of catching all exceptions. It is almost never good idea.
Upvotes: 7
Reputation: 1785
Even if you CAN catch unhandled exceptions globally, you shoud be aware that there are some exceptions that you might be able to catch, but not to handle. StackoverflowException might not leave enough stackspace to handle the exception. Same with OutOfMemory. There MIGHT not be enough space for a large object, but there's also a chance that there is no space left at all.
So you usually write code to catch and handle THOSE exceptions that you CAN handle (filenotfound, accessviolation etc) and leave all others to crash your app (better crash than continue in undefined state). The only thing you could do with an unhandled exception: TRY to gracefully close your app (saving some changes, writing an error log or whatever) and THE rethrow the exception.
Upvotes: 0
Reputation: 50712
It is not good practice to hide unhanded exception and forget about it, so don't do it.
I am not sure why you don't want to use try/catch but it is the best way to handle the situation, in which case you should fix exception if you can, or at least log it for later review
Upvotes: 0