Java 中是否可以有无 `catch` 块的 `try` 块?
可以,通过使用`final` 块,可以在没有 `catch` 块的情况下使用 `try` 块。
众所周知,`final` 块通常会执行,即使 `try` 块中出现异常,除非是 `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
`final` 块总是会执行,即使方法有返回值类型且 `try` 块返回一些值。
示例 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
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
JavaScript
PHP