Có, có thể có khối try mà không có khối catch bằng cách sử dụng khối finally.
Như chúng ta biết, khối finally luôn thực thi ngay cả khi có ngoại lệ xảy ra trong khối try, trừ trường hợp System.exit() thì nó vẫn thực thi.
Ví dụ 1
public class TryBlockWithoutCatch {
public static void main(String[] args) {
try {
System.out.println("Try Block");
} finally {
System.out.println("Finally Block");
}
}
}
Kết quả
Try Block Finally Block
Khối finally luôn thực thi ngay cả khi phương thức có kiểu trả về và khối try trả về giá trị.
Ví dụ 2
public class TryWithFinally {
public static int method() {
try {
System.out.println("Try Block with return type");
return 10;
} finally {
System.out.println("Finally Block always execute");
}
}
public static void main(String[] args) {
System.out.println(method());
}
}
Kết quả
Try Block with return type Finally Block always execute 10