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

/*
 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();

        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值