如何判断所捕获的异常类型,并根据其进行优雅处理

来源:互联网 发布:mac os x系统更新失败 编辑:程序博客网 时间:2024/06/05 00:16
/* C# typeof() 和 GetType()区是什么?1、typeof(x)中的x,必须是具体的类名、类型名称等,不可以是变量名称。 2、GetType()方法继承自Object,所以C#中任何对象都具有GetType()方法,它的作用和typeof()相同,返回Type类型的当前对象的类型。 比如有这样一个变量i: Int32 i = new Int32(); i.GetType()返回值是Int32的类型,但是无法使用typeof(i),因为i是一个变量,如果要使用typeof(),则只能:typeof(Int32),返回的同样是Int32的类型。 */using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace ConsoleApp2{    class Program    {        static void Main(string[] args)        {            try            {                byte b = 100;                byte a = (checked((byte)(b + 200)));            }            catch (Exception ex)            {                //// 1.性能低下                //OverflowException exx = new OverflowException();//构建了一个实例。浪费性能                //if (exx.GetType() == ex.GetType())                //{                //    Console.WriteLine("The exception is {0}", ex.GetType().ToString());                //}                //2. 性能优异                if (ex.GetType() == typeof(OverflowException))                {                    Console.WriteLine("The exception is {0}", ex.GetType().ToString());                }            }            Console.ReadKey();        }    }}

阅读全文
0 0