zoukankan      html  css  js  c++  java
  • 抛出异常

    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行三个异常。

  • 相关阅读:
    Python3 面向对象小练习
    Python3 面向对象进阶1
    Python3 类的继承小练习
    Python3 类的继承
    Python3 数据结构之词频统计(英文)
    Python3 类与对象之王者荣耀对战小游戏
    Python3 类与对象
    SQL优化单表案例
    SQL性能分析
    索引简介
  • 原文地址:https://www.cnblogs.com/whl4835349/p/12102037.html
Copyright © 2011-2022 走看看