ใช่ เป็นไปได้ที่จะลองบล็อกโดยไม่มีบล็อกดักจับโดยใช้บล็อกสุดท้าย
อย่างที่เราทราบกันดีว่าบล็อกสุดท้ายจะดำเนินการเสมอแม้ว่าจะมีข้อยกเว้นเกิดขึ้นในบล็อกการลอง ยกเว้น System.exit() บล็อกจะทำงานเสมอ
ตัวอย่างที่ 1
public class TryBlockWithoutCatch {
public static void main(String[] args) {
try {
System.out.println("Try Block");
} finally {
System.out.println("Finally Block");
}
}
} ผลลัพธ์
Try Block Finally Block
บล็อกสุดท้ายจะดำเนินการเสมอแม้ว่าเมธอดจะมีประเภทการส่งคืน และลองบล็อกจะคืนค่าบางส่วน
ตัวอย่างที่ 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());
}
} ผลลัพธ์
Try Block with return type Finally Block always execute 10