c#

c#拆分字符串时的异常处理

小樊
87
2024-07-04 14:25:28
栏目: 编程语言

在C#中,我们可以使用Try-Catch语句来处理字符串拆分时可能出现的异常。以下是一个示例代码:

using System;

class Program
{
    static void Main()
    {
        try
        {
            string input = "Hello World";
            string[] words = input.Split(' ');

            foreach (string word in words)
            {
                Console.WriteLine(word);
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine("An error occurred: " + ex.Message);
        }
    }
}

在上面的示例中,我们尝试将字符串“Hello World”按空格拆分为单词,并使用Try-Catch语句来捕获可能出现的异常。如果出现异常,程序将打印错误消息,否则将输出拆分后的单词。这样可以确保程序在遇到异常时不会崩溃,而是能够继续执行下去。

0
看了该问题的人还看了