√ C# - 07.怎么捕捉异常(P334)

该博客探讨了如何在C#中进行异常处理。通过使用try-catch-finally语句,可以检测可能的异常,如ArgumentException和自定义的TestException。当异常发生时,程序会匹配最合适的catch块来处理异常,并在finally块中确保特定代码始终执行。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  1. 所有异常类型都派生于Exception类。
  2. 利用关键字try检测可能出现异常的语句块,利用关键字throw抛出异常对象,利用关键字catch执行捕捉到相应异常时的语句块。
  3. 若存在多个catch块,则程序会依次寻找与检测到的异常最匹配的catch块,因此捕捉Exception异常的catch块通常是最后一个catch块。
  4. 利用关键字finally执行无论前面是否捕捉到异常都会执行的语句块。
using System;

namespace _07
{
    class Program
    {
        static void Main(string[] args)
        {
            Test.CatchException(new ArgumentException());
            Console.WriteLine();

            Test.CatchException(new TestException());
            Console.WriteLine();

            Test.CatchException(new Exception());
            Console.WriteLine();
        }
    }

    class Test
    {
        public static void CatchException(Exception exception)
        {
            try
            {
                throw exception;
            }
            catch (ArgumentException)
            {
                Console.WriteLine(new ArgumentException().Message);
            }
            catch (TestException)
            {
                Console.WriteLine(new TestException().Message);
            }
            catch (Exception)
            {
                Console.WriteLine(new Exception().Message);
            }
            finally
            {
                Console.WriteLine("Finally");
            }
        }
    }

    class TestException : Exception
    {
        public override string Message => "TestException";
    }
}

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值