Menu
CoddyTech

异常类型

本课属于 Coddy C# 学习旅程的“逻辑与流程”单元。第 24 课,共 66 课。

在 C# 中,异常会根据其表示的错误分为不同类型。了解这些类型有助于你更有效地处理错误。

我们来看看常见的异常类型:

所有异常的基类是 System.Exception。

try
{
    // 可能抛出异常的代码
}
catch (Exception ex)
{
    // 处理任何异常
    Console.WriteLine(ex.Message);
}

一些常见的异常类型:

ArgumentException:调用方法时传入无效参数会抛出此异常。

string name = null;
if (name == null)
{
    throw new ArgumentException("Name cannot be null");
}

NullReferenceException:当你尝试访问空引用上的成员时,会抛出此异常。

string text = null;
// 这会抛出 NullReferenceException 异常
int length = text.Length;

IndexOutOfRangeException:当数组索引超出数组范围时抛出。

int[] numbers = { 1, 2, 3 };
// 这会抛出 IndexOutOfRangeException 异常
int value = numbers[5];

DivideByZeroException:用整数除以零时抛出。

int result = 10 / 0; // 这会抛出 DivideByZeroException 异常

你可以捕获特定的异常:

try
{
    int[] numbers = { 1, 2, 3 };
    int value = numbers[5];
}
catch (IndexOutOfRangeException ex)
{
    Console.WriteLine("Array index error: " + ex.Message);
}
catch (Exception ex)
{
    Console.WriteLine("General error: " + ex.Message);
}
challenge icon

挑战

简单

创建一个名为 ProcessArray 的方法,该方法:

  1. 接受一个整数数组和一个索引作为参数
  2. 尝试访问指定索引处的元素
  3. 如果成功,则返回元素值
  4. 如果发生 IndexOutOfRangeException,则捕获该异常并返回 -1

你的方法应具有以下签名:

public static int ProcessArray(int[] array, int index)

亲手试试

using System;

class Program
{
    public static int ProcessArray(int[] array, int index)
    {
        // 在这里编写你的代码
        return 0;
    }

    static void Main(string[] args)
    {
        // 读取数组输入
        string input = Console.ReadLine();
        
        // 如果有方括号,就将其去掉
        if (input.StartsWith("[") && input.EndsWith("]"))
        {
            input = input.Substring(1, input.Length - 2);
        }
        
        string[] parts = input.Split(',');
        
        int[] array = new int[parts.Length];
        for (int i = 0; i < parts.Length; i++)
        {
            array[i] = int.Parse(parts[i].Trim());
        }
        
        // 读取索引输入
        int index = int.Parse(Console.ReadLine());
        
        int result = ProcessArray(array, index);
        Console.WriteLine(result);
    }
}
quiz icon自我测试

这节课包含一个小测验。开始学习即可作答,并记录你的进度。

逻辑与流程中的所有课

自己练习: C# 在线编译器