using System;
using System.Threading;
namespace ConsoleHelper
{
internal class Program
{
static void Main(string[] args)
{
var t = new Thread(FaultyThread); // 好例子
t.Start();
t.Join();
Console.WriteLine("请按回车!");
Console.ReadLine();
Console.WriteLine("主线程中无法获得异常的打印"); // 不好的例子
try
{
t = new Thread(BadFaultyThread);
t.Start();
}
catch (Exception ex)
{
Console.WriteLine("we won`t get here!");
}
Console.ReadLine();
}
public 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);
}
}
public static void BadFaultyThread() // 异常捕获,不好的例子
{
Console.WriteLine("Starting a faulty thread...");
Thread.Sleep(TimeSpan.FromSeconds(2));
throw new Exception("Boom!");
}
}
}
列举了两个例子;推荐在线程内部来捕获线程的异常。在主线程中无法捕获线程异常。