Java 中是否可以有无 `catch` 块的 `try` 块?


可以,通过使用`final` 块,可以在没有 `catch` 块的情况下使用 `try` 块。

众所周知,`final` 块通常会执行,即使 `try` 块中出现异常,除非是 `System.exit()`, 它将始终执行。

示例 1

Open Compiler
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

`final` 块总是会执行,即使方法有返回值类型且 `try` 块返回一些值。

Learn Java in-depth with real-world projects through our Java certification course. Enroll and become a certified expert to boost your career.

示例 2

Open Compiler
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 

更新于: 2023-11-21

2.9 万+ 浏览量

开启你的职业生涯

完成课程以获得认证

开始
广告