前言
try-catch-finally是一种异常处理机制,用于在程序执行过程中捕获和处理异常。try块中包含可能会抛出异常的代码,catch块用于捕获并处理try块中抛出的异常,finally块中的代码无论是否发生异常都会被执行。
下面列出几个经常出现的使用场景,可以运行一下代码,观察一下执行顺序和结果。
一、示例代码
(1)Main.java
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.ArrayList;
import java.util.List;
public class Main {
/**
* 自定义异常
*/
static class CustomException extends Exception {
public CustomException(String message) {
super(message);
}
}
/**
* try-catch-finally 无异常
* 说明:若 finally 代码块有 return 语句,则 return 的优先级比 try、catch 还要高
* 一般不建议 finally 代码块有 return 语句,这样会破坏程序的完整性
*/
public static int fn_1() {
try {
return 1;
} catch (Exception e){
return 0;
} finally {
return 666;
}
}
/**
* try-catch 自定义异常
* 说明:catch 捕获到了异常
*/
public static int fn_2() {
try {
if (true)
throw new CustomException("Some error message");
return 1;
} catch (Exception e){
return 0;
}
}
/**
* try-catch-finally 嵌套
* 说明:若里面的 catch 捕获异常而无向外面抛出,则外面的 catch 无法捕获内部的异常
*/
public static int fn_3() {
try {
try {
if (true)
throw new CustomException("Some error message");
} catch (CustomException ce) {
// throw new RuntimeException(ce);
}
return 1;
} catch (Exception e) {
return 0;
}
}
/**
* try-catch-finally 基本数据类型
*/
public static boolean fn_4 () {
boolean a;
try {
a = false;
int b = 10 / 0;
return a;
} catch (Exception e){
a = true;
return a;
} finally {
a = false;
}
}
/**
* try-catch-finally 引用类型
*/
public static List<Integer> fn_5() {
List<Integer> list = new ArrayList<>();
try {
list.add(1);
int n = 1 / 0;
return list;
} catch (Exception e) {
list.add(2);
return list;
} finally {
list.add(3);
}
}
/**
* try-catch-finally 引用类型
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
static class User {
private String username;
}
public static User fn_6() {
User user = new User();
try {
user.setUsername("try");
int n = 1 / 0;
return user;
} catch (Exception e) {
user.setUsername("catch");
return user;
} finally {
user.setUsername("finally");
}
}
/**
* try-catch 里面使用循环语句
*/
public static void fn_7() {
try {
for (int i = 0; i < 5; i++) {
if (i == 2){
int n = 1 / 0;
}
System.out.println(i);
}
} catch (Exception e) {
// Todo
}
}
/**
* try-catch 外面使用循环语句
*/
public static void fn_8() {
for (int i = 0; i < 5; i++) {
try {
if (i == 2){
int n = 1 / 0;
}
System.out.println(i);
} catch (Exception e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
// int res_1 = Main.fn_1();
// System.out.println(res_1); // 666
// int res_2 = Main.fn_2();
// System.out.println(res_2); // 0
// int res_3 = Main.fn_3();
// System.out.println(res_3); // 1
// boolean res_4 = Main.fn_4();
// System.out.println(res_4); // true
// List<Integer> res_5 = Main.fn_5();
// System.out.println(res_5); // [1, 2, 3]
// User res_6 = Main.fn_6();
// System.out.println(res_6); // finally
// Main.fn_7(); // 0 1
// Main.fn_8(); // 0 1 3 4
}
}
二、运行效果
见程序输出。