在C#编程中,异常处理由try/catch语句执行。C#中的try block用于放置可能引发异常的代码。catch block用于处理异常。
不带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); }
</span><span class="typ">Console</span><span class="pun">.</span><span class="typ">WriteLine</span><span class="pun">(</span><span class="str">"Rest of the code"</span><span class="pun">);</span><span class="pln">
</span><span class="pun">}</span><span class="pln">
}
输出:
System.DivideByZeroException: Attempted to divide by zero. Rest of the code