抛出异常

https://www.cnblogs.com/OpenCoder/p/6208284.html

throw 和throw  ex 抛出异常的区别

throw  ex

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ExceptionTesting
{
    class Program
    {
        static void InnerException()
        {
            throw new Exception("模拟异常");
        }

        static void OuterException()
        {
            try
            {
                InnerException();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        static void Main(string[] args)
        {
            try
            {
                OuterException();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.StackTrace);//由于代码24行使用throw ex重置了异常抛出点,所以这里异常堆栈只能捕捉到代码32行和24行抛出的异常,但是13行的异常在堆栈中无法捕捉到
            }

            Console.ReadLine();
        }
    }
}

  可以看到使用throw ex会使得C#重置代码中异常的抛出点,从而让C#认为异常的原始抛出点应该是在代码24行,在异常堆栈中无法捕捉到代码13行所抛出的异常。

thow

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ExceptionTesting
{
    class Program
    {
        static void InnerException()
        {
            throw new Exception("模拟异常");
        }

        static void OuterException()
        {
            try
            {
                InnerException();
            }
            catch(Exception ex)
            {
                throw;
            }
        }

        static void Main(string[] args)
        {
            try
            {
                OuterException();
            }
            catch(Exception ex)
            {
                Console.WriteLine(ex.StackTrace);//由于现在代码24行使用了throw抛出捕获到的异常,并没有重置原始异常的抛出点,所以这里异常堆栈不但能捕捉到代码32行和24行抛出的异常,还能捕捉到代码13行抛出的异常。
            }

            Console.ReadLine();
        }
    }
}

由于这一次我们使用了throw来抛出代码24行中catch代码块中捕获到的异常,并没有重置异常的抛出点,因此在上面代码36行这一次异常堆栈输出了13行、24行、32行三个异常。

 

posted @ 2019-12-26 14:52  wonderfulviews  阅读(166)  评论(0编辑  收藏  举报