C#教程
C#控制语句
C#函数
C#数组
C#面向对象
C#命名空间和异常
C#文件IO
C#集合
C#多线程
C#其它

C# try/catch

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# try/catch 示例

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
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4