个性化阅读
专注于IT技术分析

C# try-catch用法

在C#编程中,异常处理是通过try / catch语句执行的。 C#中的try块用于放置可能引发异常的代码。 catch块用于处理异常。 catch块之前必须是try块。

没有try / catch的C#示例

using System;
public class ExExample
{
    public static void Main(string[] args)
    {
        int a = 10;
        int b = 0;
        int x = a/b;  
        Console.WriteLine("Rest of the code");
    }
}

输出:

Unhandled Exception: System.DivideByZeroException: Attempted to divide by zero.

C#尝试/捕获示例

using System;
public class ExExample
{
    public static void Main(string[] args)
    {
        try
        {
            int a = 10;
            int b = 0;
            int x = a / b;
        }
        catch (Exception e) { Console.WriteLine(e); }

        Console.WriteLine("Rest of the code");
    }
}

输出:

System.DivideByZeroException: Attempted to divide by zero.
Rest of the code
赞(0)
未经允许不得转载:srcmini » C# try-catch用法

评论 抢沙发

评论前必须登录!