原则:线程都不应该抛出未捕获的exception,也就是说各个线程需要自己把自己的checked exception处理掉。
话不多说,直接看代码
static void Main(string[] args)
{ //第一个会抛出异常的线程(但这个线程方法内部作了异常捕获和处理)【正确的作法】
var t = new Thread(FaultyThread);
t.Start();
t.Join();
try
{
//第二个会抛出异常的线程(这个线程方法内部没作异常捕获和处理)【错误的作法】 t = new Thread(BadFaultyThread);
t.Start();
}
catch (Exception ex)
{ //代码并不会运行到这里,也就是说并不能捕获到线程内部的异常
Console.WriteLine("We won't get here!");
}
Console.Read();
}
static void BadFaultyThread()
{
Console.WriteLine("Starting a faulty thread...");
Thread.Sleep(TimeSpan.FromSeconds(2));
throw new Exception("Boom!");
}
static void FaultyThread()
{
try
{
Console.WriteLine("Starting a faulty thread...");
Thread.Sleep(TimeSpan.FromSeconds(1));
throw new Exception("Boom!");
}
catch (Exception ex)
{
Console.WriteLine("Exception handled: {0}", ex.Message);
}
}
再来看一下,下面的运行结果就明白了

来源:https://www.cnblogs.com/gougou1981/p/12332955.html