Thuta Learning
ရှာဖွေရန်
AdvancedProgrammingbeginner

Exceptions

စိတ်လျှော့ပါ။ ဒီခန်းကို စာအုပ်လိုမဟုတ်ဘဲ စကားပြောသလိုပဲ၊ နားလည်လွယ်အောင် ရှင်းပါမယ်။

Program တစ်ခုမှာ error ဖြစ်နိုင်တဲ့နေရာတွေ အမြဲရှိပါတယ်။ File မတွေ့တာ၊ network fail ဖြစ်တာ၊ array index မှားတာ၊ user input မမှန်တာ စတာတွေပါ။ Exception Handling က error ဖြစ်တဲ့အခါ app တစ်ခုလုံး crash မဖြစ်အောင် လုံခြုံစွာကိုင်တွယ်ပေးပါတယ်။

csharp
try
{
    int[] numbers = { 1, 2, 3 };
    Console.WriteLine(numbers[10]);
}
catch (IndexOutOfRangeException)
{
    Console.WriteLine("Index is outside the array range.");
}
catch (Exception ex)
{
    Console.WriteLine("Something went wrong.");
    Console.WriteLine(ex.Message);
}
finally
{
    Console.WriteLine("Finished checking the array.");
}

try, catch, finally

  • try ထဲမှာ error ဖြစ်နိုင်တဲ့ code ကိုထားပါတယ်။
  • catch က error ဖြစ်လာရင် ကိုင်တွယ်ပါတယ်။ Specific exception ကိုအရင်ဖမ်းတာက ပိုကောင်းပါတယ်။
  • finally က error ဖြစ်ဖြစ် မဖြစ်ဖြစ် run ပါတယ်။ Resource cleanup လုပ်ဖို့အသုံးဝင်ပါတယ်။
You should see
Index is outside the array range. Finished checking the array.

Info

⚠️ Best practice

Error ကို မျက်လုံးပိတ်ပြီးဖျောက်ပစ်တာမျိုး မလုပ်ပါနဲ့။ User ကို friendly message ပြပြီး developer အတွက် log သိမ်းထားတာက ပိုကောင်းပါတယ်။

Exceptions | Thuta Learning