在C#的for循環(huán)中進(jìn)行異常處理,可以使用try-catch語(yǔ)句。將可能引發(fā)異常的代碼放在try塊中,然后在catch塊中處理異常。這是一個(gè)示例:
using System;
class Program
{
static void Main()
{
for (int i = 0; i < 10; i++)
{
try
{
// 將可能引發(fā)異常的代碼放在try塊中
int result = Divide(i, i - 5);
Console.WriteLine($"Result: {result}");
}
catch (DivideByZeroException ex)
{
// 在catch塊中處理異常
Console.WriteLine($"Error: {ex.Message}");
}
}
}
static int Divide(int a, int b)
{
return a / b;
}
}
在這個(gè)示例中,我們?cè)趂or循環(huán)中調(diào)用了Divide
方法,該方法可能會(huì)引發(fā)DivideByZeroException
異常。我們將這個(gè)方法放在try塊中,并在catch塊中捕獲和處理異常。這樣,即使發(fā)生異常,程序也會(huì)繼續(xù)執(zhí)行下一次循環(huán)。