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