1.12 Handling Exceptions

  • The code describes the thread how to correctly handle exceptions. Always use the try-catch block in the thread is very important, because it is impossible outside the thread code to catch the exception.
 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);
            }
        }
    }
  • Code Interpretation:

    Throws define two threads, without a try-catch process, there is another process. You can see the Main method where the exception is not to capture the try-cath. So if you use threads, generally do not throw an exception in the thread, but try-catch block in the threaded code. That is only to deal with the thread calls a function in the inside, the outside is not receiving thread of error

    In older versions of .net 1.0 or 1.1, the behavior is not the same, the exception does not force the program uncaught closed. You can use this policy by adding a includes the following configuration.

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

Guess you like

Origin www.cnblogs.com/anjun-xy/p/11748231.html