try {
int result = 10 / 0; // Ném ArithmeticException} catch (ArithmeticException e) {
System.out.println("Không thể chia cho 0");
} finally {
System.out.println("Luôn được thực thi");
}
3) Multiple catch blocks
try {
int[] arr =newint[5];
arr[10]= 50; // ArrayIndexOutOfBoundsExceptionint num = Integer.parseInt("abc"); // NumberFormatException} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Lỗi truy cập mảng");
} catch (NumberFormatException e) {
System.out.println("Lỗi chuyển đổi số");
} catch (Exception e) { // Bắt tất cả exception khác System.out.println("Lỗi: "+ e.getMessage());
}
4) Throw và Throws
publicclassAgeValidator {
publicstaticvoidvalidateAge(int age) throws IllegalArgumentException {
if (age < 0) {
thrownew IllegalArgumentException("Tuổi không được âm");
}
if (age > 150) {
thrownew IllegalArgumentException("Tuổi không hợp lệ");
}
}
publicstaticvoidmain(String[] args) {
try {
validateAge(-5);
} catch (IllegalArgumentException e) {
System.out.println("Lỗi: "+ e.getMessage());
}
}
}