如何處理例外錯誤狀況 應用介紹-[try-catch-finally]
1.) NG程式
//錯誤程式,程式直接當掉(原因被除數不得維0)
private void button1_Click(object sender, EventArgs e)
{
int a = 0;
int b =100/a;
Console.WriteLine("b is {0}", b);
Console.WriteLine("End of job ");
}
2.) 攔截NG程式
//try-catch-finally語法(程式不會當掉,但提報錯誤)
private void button2_Click(object sender, EventArgs e)
{
int a = 0;
try
{
int b = 100 / a;
Console.WriteLine("b is {0}", b);
}
//錯誤攔截訊息
catch (Exception err1)
{
Console.WriteLine("Divided by zero ");
Console.WriteLine("Divided by zero {0}",err1 );
MessageBox.Show(err1.ToString ());
}
//最後一定會執行
finally
{
Console.WriteLine("End of job");
}
3.) 自行判斷NG錯誤跳轉攔截錯誤訊息(throw 使用)
//自行判斷錯誤跳轉攔截錯誤訊息(程式不會當掉,但提報錯誤)
private void button3_Click(object sender, EventArgs e)
{
int a = 100, b = 0;
try
{
if (b == 0)
{
//跳轉呼叫丟出錯誤
throw new ArithmeticException("Div by zero");
}
else
{
int c = a / b;
Console.WriteLine("Resoult is " + c);
}
Console.WriteLine("After divide2");
}
//
catch (ArithmeticException error)
{
Console.WriteLine("Caught!{0}",error );
}
===========================================
自訂錯誤類別-待續
2010年1月26日 星期二
訂閱:
張貼留言 (Atom)
沒有留言:
張貼留言