วันพฤหัสบดีที่ 10 กรกฎาคม พ.ศ. 2551

ลำดับการเรียก Exception ใน C#

การเกิด Exception ใน C# กรณีที่เป็น Nested ให้พิจารณาตัวอย่างต่อไปนี้


using System;
using System.Text;

namespace DemoEsception
{
class Program
{
static void Main(string[] args)
{
try
{
Console.WriteLine("Point A");
try
{
Console.WriteLine("Point B");
// Try to convert wrong format
Console.WriteLine(int.Parse("abc"));
Console.WriteLine("Point C");
}
catch (FormatException e)
{
Console.WriteLine("Catch exception:{0}",e);
}
Console.WriteLine("Point D");
}
catch (Exception e)
{
Console.WriteLine("Outer exception:{0}",e);
}
Console.WriteLine("Point E");
Console.ReadKey();
}
}
}


ผลลัพธ์ที่ได้
Point A
Point B

Catch exception:System.FormatException: Input string was not in a correct format. at System.Number.StringToNumber(String str, NumberStyles options, NumberBuffer& number, NumberFormatInfo info, Boolean parseDecimal) at System.Number.ParseInt32(String s, NumberStyles style, NumberFormatInfo info) at System.Int32.Parse(String s) at DemoEsception.Program.Main(String[] args) in D:\Data\Visual Studio 2008\Projects\DemoEsception\DemoEsception\Program.cs:line 17
Point D
Point E


สังเกตว่าใน code นี้เกิดความผิดพลาดขึ้นเมื่อเกิดความพยายามเปลี่ยนตัวอักษร abc ให้เป็นตัวเลขโดยใช้คำสั่ง int.Parse("abc") ซึ่งจะทำให้เกิด FormatException ขึ้น และเมื่อเกิด Exception ขึ้นนั้นโปรแกรมจะข้าม Point C แล้วทำงานในส่วนของ exception แล้วกลับไปทำงานยัง Point D และ Point E จะเห็นว่าโปรแกรมจะไม่เข้าไปดำเนินการ exception ด้านนอกเนื่องจากได้ดำเนินการ FormatException ไปเรียบร้อยแล้ว

พิจาณา Code ต่อไปนี้เพิ่มเติม

using System;
using System.Text;

namespace DemoEsception
{
class Program
{
static void Main(string[] args)
{
try
{
Console.WriteLine("Point A");
try
{
Console.WriteLine("Point B");
// Try to convert wrong format
Console.WriteLine(int.Parse("abc"));
Console.WriteLine("Point C");
}
catch (IndexOutOfRangeException e)
{
Console.WriteLine("Catch exception:{0}",e);
}
Console.WriteLine("Point D");
}
catch (Exception e)
{
Console.WriteLine("Outer exception:{0}",e);
}
Console.WriteLine("Point E");
Console.ReadKey();
}
}
}

ผลลัพธ์ที่ได้
Point A
Point B
Outer exception:System.FormatException: Input string was not in a correct format. at System.Number.StringToNumber(String str, NumberStyles options, NumberBuffer& number, NumberFormatInfo info, Boolean parseDecimal) at System.Number.ParseInt32(String s, NumberStyles style, NumberFormatInfo info) at System.Int32.Parse(String s) at DemoEsception.Program.Main(String[] args) in D:\Data\Visual Studio 2008\Projects\DemoEsception\DemoEsception\Program.cs:line 17
Point E

จากตัวอย่างข้างต้นได้เปลี่ยนแปลง Exception เป็น IndexOutOfRangeException ซึ่งทำให้เกิด exception ที่ไม่ได้ดักจับไว้ ผลคือ โปรแกรมจะข้ามการดำเนินการ exception ภายในไปยัง exception ภายนอกซึ่งไม่ได้กำหนดชนิดของ exception ไว้จึงทำให้ การดำเนินการใน Point C และ Point D ถูกข้ามไป เมื่อทำงานในส่วน exception เสร็จแล้วโปรแกรมจึงกลับมาดำเนินการใน Point E ต่อไป