C# 教程:第八章:异常处理

1. 异常的概念

异常是程序在运行时出现的错误情况。它们中断程序的正常执行流,可以通过异常处理机制来捕获和处理异常,以便程序能够继续运行或适当地终止。

  • 常见异常类型

    • System.NullReferenceException:访问空对象引用。
    • System.IndexOutOfRangeException:数组索引超出范围。
    • System.DivideByZeroException:除数为零。
  • 异常的层次结构
    异常类派生自 System.Exception 类,常见的异常类包括 System.ApplicationExceptionSystem.SystemException

2. try-catch语句

try-catch 语句用于捕获和处理异常。

  • 基本语法

    try {
        // 可能产生异常的代码
    }
    catch (ExceptionType ex) {
        // 处理异常的代码
    }
    
  • 示例

    try {
        int[] numbers = { 1, 2, 3 };
        Console.WriteLine(numbers[5]);
    }
    catch (IndexOutOfRangeException ex) {
        Console.WriteLine("Index out of range: " + ex.Message);
    }
    

在这个例子中,访问数组超出范围会抛出 IndexOutOfRangeException 异常,被 catch 块捕获并处理。

3. finally块

finally 块用于执行一些必须要运行的代码,无论是否发生异常。

  • 基本语法

    try {
        // 可能产生异常的代码
    }
    catch (ExceptionType ex) {
        // 处理异常的代码
    }
    finally {
        // 总是执行的代码
    }
    
  • 示例

    try {
        int number = int.Parse("abc");
    }
    catch (FormatException ex) {
        Console.WriteLine("Format error: " + ex.Message);
    }
    finally {
        Console.WriteLine("This code runs regardless of whether an exception was thrown.");
    }
    

在这个例子中,finally 块中的代码无论是否发生异常都会执行。

4. 自定义异常

你可以定义自己的异常类,以提供更详细的错误信息。

  • 自定义异常类

    public class MyCustomException : Exception {
        public MyCustomException() { }
    
        public MyCustomException(string message)
            : base(message) { }
    
        public MyCustomException(string message, Exception inner)
            : base(message, inner) { }
    }
    
  • 抛出和捕获自定义异常

    public class Example {
        public void DoSomething(int value) {
            if (value < 0) {
                throw new MyCustomException("Value cannot be negative.");
            }
        }
    }
    
    // 使用自定义异常
    try {
        Example example = new Example();
        example.DoSomething(-1);
    }
    catch (MyCustomException ex) {
        Console.WriteLine("Custom error: " + ex.Message);
    }
    

在这个例子中,MyCustomException 是一个自定义异常类,可以在特定情况下抛出并捕获,以便提供更有意义的错误信息。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

风不归Alkaid

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值