1.12 处理异常

  • 本代码介绍了在线程中如何正确处理异常。在线程中始终使用try-catch代码块非常重要,因为不可能在线程代码之外来捕获异常。
 static void Main(string[] args)
        {

            #region 1.12
            var t = new Thread(Class1_12.FaultyThread);
            t.Start();
            t.Join();
            try
            {
                t = new Thread(Class1_12.BadFaultyThread);
                t.Start();
            }
            catch (Exception ex)
            {
                Console.WriteLine("到不了这里 " );
            }
            #endregion
}

public class Class1_12
{
        //抛异常线程(没有捕获)
        public static void BadFaultyThread()
        {
            Console.WriteLine("启动一个错误的线程1 ...");
            Thread.Sleep(TimeSpan.FromSeconds(2));
            throw new Exception("Boom!");
        }
        //抛异常线程(有捕获)
        public static void FaultyThread()
        {
            try
            {
                Console.WriteLine("启动一个错误的线程2 ...");
                Thread.Sleep(TimeSpan.FromSeconds(1));
                throw new Exception("Boom!");
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception handled: {0}", ex.Message);
            }
        }
    }
  • 代码解读:

    定义两个抛异常的线程,一个没有try-catch处理,另一个有处理。可以看到Main方法里异常没有被try-cath捕获到。所以如果使用线程,一般不要在线程中抛异常,而是在线程代码中try-catch代码块。即只能在线程调用中的函数里面去处理,在外面是接收不到线程中的报错的

    在比较老版本的.net 1.0或1.1,该行为是不一样的,未被捕获的异常不会强制程序关闭。可以通过添加一个包含下列配置来使用该策略。

    <configuration>
      <runtime>
          <legacyUnhandledExceptionPolicy enabled="1"/>
      </runtime>
    </configuration>

猜你喜欢

转载自www.cnblogs.com/anjun-xy/p/11748231.html