Morten,
That's not completely true. You can have multiple threads in a console
application, and if an exception is thrown on one of those threads, then you
will not catch it by wrapping the code in a try/catch block. Take for
example the following code:
static void Main(string[] args)
{
try
{
// Create a thread.
Thread pobjThread = new Thread(new ThreadStart(DoSomething));
// Start the thread.
pobjThread.Start();
// Wait five seconds.
Thread.Sleep(5000);
}
catch (Exception e)
{
Console.WriteLine("Exception on Main thread:")
Console.WriteLine(e);
}
// Get out.
return;
}
private static void DoSomething()
{
// Throw an exception.
throw new Exception();
}
This will crash and not be caught by the catch block.
Rather, you need to attach to the UnhandledException event on the
current AppDomain, like this:
static void Main(string[] args)
{
// Wire up an event handler for unhandled exceptions.
AppDomain.CurrentDomain.UnhandledException += new
UnhandledExceptionEventHandler(UnhandledException) ;
try
{
// Create a thread.
Thread pobjThread = new Thread(new ThreadStart(DoSomething));
// Start the thread.
pobjThread.Start();
// Wait five seconds.
Thread.Sleep(5000);
}
catch (Exception e)
{
Console.WriteLine(e);
}
// Get out.
return;
}
private static void UnhandledException(object sender,
UnhandledExceptionEventArgs e)
{
// Write the exception.
Console.WriteLine("AppDomain Unhandled Exception Event Handler:");
Console.WriteLine(e.ExceptionObject);
}
private static void DoSomething()
{
// Throw an exception.
throw new Exception();
}
}
Hope this helps.
--
- Nicholas Paldino [.NET/C# MVP]
-
mv*@spam.guard.caspershouse.com
"Morten Wennevik" <Mo************@hotmail.com> wrote in message
news:oprzyxozmvhntkfz@localhost...
put all code in Main() inside a try/catch(/finally) block.
Main is where your program starts and any exception not caught elsewhere
in your code will end up in main before your program crashes.
--
Using M2, Opera's revolutionary e-mail client:
http://www.opera.com/m2/