Exception Handling သည် runtime မှာ error ဖြစ်လာရင် program တစ်ခုလုံး crash မဖြစ်အောင်ထိန်းပေးတဲ့နည်းလမ်းပါ။ Error ဖြစ်နိုင်တဲ့ code ကို try ထဲထည့်ပြီး error ဖြစ်လာရင် catch ကကိုင်တွယ်ပါတယ်။ finally သည် error ဖြစ်ဖြစ် မဖြစ်ဖြစ် run ပါတယ်။
java
public class Main {
public static void main(String[] args) {
try {
int[] numbers = {10, 20, 30};
System.out.println(numbers[5]);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Invalid index. Please choose an item inside the array.");
} finally {
System.out.println("Array check finished.");
}
}
}Array ထဲမှာ index 0,1,2 ပဲရှိပေမယ့် numbers[5] ကိုခေါ်ထားလို့ exception ဖြစ်ပါတယ်။ catch block က error ကိုဖမ်းပြီး user-friendly message ထုတ်ပေးပါတယ်။
You should see
Invalid index. Please choose an item inside the array. Array check finished.လက်တွေ့အသုံးချမှု
File reading, API calls, database queries, payment requests, user input parsing တွေမှာ exception handling မရှိရင် production app ကအလွယ်တကူ crash ဖြစ်နိုင်ပါတယ်။