Exception Propagation เข้าใจได้จากการทำงานของ exception handling ใน C#
ใน try เมื่อ exception เกิดขึ้น catch blocks ที่ตรงกันจะถูกตรวจสอบ ถ้าไม่มี catch ที่ตรง exception จะถูกส่งต่อ (propagate) ไปยัง try block ระดับสูงกว่า ทำซ้ำจนกว่าจะจับได้ ถ้าไม่จับได้ โปรแกรมจะจบการทำงาน
แนวคิดนี้อธิบายในตัวอย่าง nested try statements:
ตัวอย่าง
using System;
using System.Text;
public class Demo {
public static void Main() {
try {
try { throw new ArgumentException(); }
catch (NullReferenceException e) { Console.WriteLine("catch one"); }
finally { Console.WriteLine("finally one"); }
}
catch (Exception e) { Console.WriteLine("catch two"); }
finally { Console.WriteLine("finally two"); }
Console.ReadLine();
}
}
ผลลัพธ์
finally one catch two finally two