Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

c# throw

作者:★执着唯她   发布日期:2026-05-15   浏览:64

// 示例代码:使用 throw 抛出异常

using System;

class Program
{
    static void Main()
    {
        try
        {
            int[] numbers = { 1, 2, 3 };
            Console.WriteLine("数组的第5个元素是: " + GetElement(numbers, 5));
        }
        catch (IndexOutOfRangeException ex)
        {
            Console.WriteLine("捕获到异常: " + ex.Message);
        }
    }

    static int GetElement(int[] array, int index)
    {
        if (index >= array.Length || index < 0)
        {
            // 抛出 IndexOutOfRangeException 异常
            throw new IndexOutOfRangeException("索引超出范围。");
        }
        return array[index];
    }
}

解释说明:

  • throw 关键字用于显式地抛出一个异常。
  • 在上面的示例中,GetElement 方法检查传入的索引是否在数组的有效范围内。如果索引无效,则使用 throw 抛出一个 IndexOutOfRangeException 异常,并提供一个自定义的错误消息。
  • Main 方法中,我们使用 try-catch 块来捕获并处理这个异常,避免程序崩溃,并输出友好的错误信息。

上一篇:c# 数组转字符串

下一篇:c# npoi

大家都在看

c# 二进制

c# 创建目录

c# socket服务端连接多个客户端

c# datatable group by

c# tcp client

c# type.gettype

c# sqlconnection

c# string.format 小数位数

c# invoke方法

.net和c#

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站