在 C# 编程中,异常处理是通过 try/catch 语句执行的。C# 中的try 块用于放置可能抛出异常的代码。catch 块用于处理异常。catch 块必须在 try 块之前。
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:试图除以零。
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