Try và Catch trong Java
Một method bắt exception dùng kết hợp từ khóa try và catch. Khối try/catch bao quanh code có thể ném exception.
Cú pháp
try {
// Protected code
} catch (ExceptionName e1) {
// Catch block
}
Khối catch khai báo kiểu exception muốn bắt. Nếu exception xảy ra trong protected code, các catch block sau try được kiểm tra. Nếu kiểu exception khớp, exception được truyền vào catch block như tham số method.
Ví dụ Try-Catch
import java.io.*;
public class Demo {
public static void main(String args[]) {
try {
int a[] = new int[5];
System.out.println("Access element eighth: " + a[7]);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Exception thrown: " + e);
}
System.out.println("Out of the block");
}
}
Kết quả
Exception thrown: java.lang.ArrayIndexOutOfBoundsException: 7 Out of the block
Throw và Throws trong Java
throws: Nếu method không handle checked exception, phải khai báo nó dùng từ khóa throws. throws xuất hiện ở cuối signature của method. Dùng để trì hoãn xử lý checked exception.
throw: Dùng để ném exception một cách explicit (tự ý), có thể là exception mới tạo hoặc exception vừa bắt được.
Tóm tắt: throws khai báo method có thể ném exception (delegate cho caller), throw chủ động ném exception instance.
Ví dụ throws
public void readFile(String path) throws IOException {
FileInputStream fis = new FileInputStream(path);
// ...
}
Ví dụ throw
public void setAge(int age) {
if (age < 0) {
throw new IllegalArgumentException("Age cannot be negative");
}
this.age = age;
}