Java - try-catch-finally 的基本用法

前言

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
    }
}

二、运行效果

见程序输出。

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值