try中的程序塊是有可能發生錯誤的程序塊,catch中的程序塊是當發生錯誤的時候才會執行的代碼塊,finally中的程序塊是無論是否發生錯誤都會執行的代碼塊。
示例程序:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Sample_01_CA
{
public class Complex
{
static void Main(string[] args)
{
int i = 2008;
int j = 0;
try
{
int result = i / j;
}
catch
{
Console.WriteLine("J變量的值為0");
}
finally
{
Console.WriteLine(j.ToString());
}
Console.Read();
}
};
}J變量的值為0
0
示例程序:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Sample_01_CA
{
public class Complex
{
static void Main(string[] args)
{
int i = 2008;
int j = 2;
try
{
int result = i / j;
}
catch
{
Console.WriteLine("J變量的值為0");
}
finally
{
Console.WriteLine(j.ToString());
}
Console.Read();
}
};
}
0