C# 属性

C# 抽象

C# 字符串

C# 泛型

C# 杂项

C# 新特性

C# try/catch 尝试/捕获

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

没有 try/catch 的 C# 示例

例子 (Example)

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");  
    }  
}

输出:

未处理的异常:System.DivideByZeroException:试图除以零。

C# 尝试/捕获示例

例子 (Example)

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


上一主题 C# 异常处理 下一主题 C# finally 始终运行
  • 使用社交账号登录,本站支持
全部评论(0)