চেইন্ড এক্সেপশন হল এক্সেপশন হ্যান্ডলিং-এ একটি প্যাটার্ন যেখানে ক্যাচ করা এক্সেপশনকে নতুন এক্সেপশনে র্যাপ করে রিথ্রো করা হয়, মূল এক্সেপশনটি InnerException প্রোপার্টিতে সংরক্ষণ থাকে। এটি ডিবাগিং সহজ করে।
কনস্ট্রাক্টর
throw new Exception("নতুন মেসেজ", originalException); // InnerException সেট হয়
চেইনিং প্যাটার্ন (লেভেলড)
static void Main()
{
try { Level1(); }
catch (Exception ex) { Console.WriteLine(ex); }
}
static void Level1()
{
try { Level2(); }
catch (Exception ex) { throw new Exception("Level 1 failed", ex); }
}
static void Level2()
{
try { Level3(); }
catch (Exception ex) { throw new Exception("Level 2 failed", ex); }
}
static void Level3()
{
try { Level4(); }
catch (Exception ex) { throw new Exception("Level 3 failed", ex); }
}
static void Level4()
{
throw new Exception("Root cause: Database connection failed");
}
আউটপুট (স্ট্যাক ট্রেস)
System.Exception: Level 1 failed
---> System.Exception: Level 2 failed
---> System.Exception: Level 3 failed
---> System.Exception: Root cause: Database connection failed
--- End of inner exception stack trace ---
at Level3()
--- End of inner exception stack trace ---
at Level2()
--- End of inner exception stack trace ---
at Level1()
--- End of inner exception stack trace ---
at Main()
InnerException এক্সেস করা
try { RiskyOperation(); }
catch (Exception ex)
{
Console.WriteLine("Main Error: " + ex.Message);
Exception current = ex;
int level = 0;
while (current != null)
{
Console.WriteLine($" Level {level++}: {current.Message}");
current = current.InnerException;
}
}
সেরা অনুশীলন
- কখনোই
throw ex;করবেন না — স্ট্যাক ট্রেস হারিয়ে যায়।throw;ব্যবহার করুন। - কনটেক্সট যোগ করতে
throw new CustomException("Context", ex);করুন। - কাস্টম এক্সেপশন ক্লাসে
InnerExceptionকনস্ট্রাক্টর রাখুন। - গ্লোবাল এক্সেপশন হ্যান্ডলারে লগিং-এ ফুল চেইন অন্তর্ভুক্ত করুন।
Anti-Pattern (বچুন)
// খারাপ: স্ট্যাক ট্রেস হারায়
catch (Exception ex) { throw new Exception("Error"); }
// ভালো: চেইন রক্ষা
catch (Exception ex) { throw new Exception("Error", ex); }
// সেরা: শুধু রিথ্রো (কনটেক্সট দরকার নেই)
catch { throw; }