try-catch-finally 在JS中的执行顺序

绪论

看到一篇文章,介绍 try-catch-finally 的执行顺序,在此记录一下。回头再试试Java中是不是也这样。

正文

<!DOCTYPE html>
<div lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>aa</title>
    <script src="js/jquery-2.2.4.min.js"></script>
    <link rel="stylesheet" type="text/css" href="css/index.css">
    <style>
       
    </style>
</head>

<body>

</body>
<script>
    $(document).ready(function () {
        test();
        console.log(test1());
        console.log(test2());
        console.log(test3());
    });

    // 执行顺序test_try、test_finally
    function test() {
        try {
            console.log('test_try');
        } finally {
            console.log('test_finally'); 
        }
    }

    // 执行顺序test_1_try、test_1_finally、test_1_try_return
    function test1() {
        try {
            console.log('test_1_try');
            return 'test_1_try_return';
        } finally {
            console.log('test_1_finally'); 
        }
    }

	// 执行顺序test_2_try、test_2_finally、test_2_finally_return
    function test2() {
        try {
            console.log('test_2_try');
            return 'test_2_try_return';
        } finally {
            console.log('test_2_finally');
            return 'test_2_finally_return';
        }
    }

	// 执行顺序test_3_try、throw、test_3_finally、test_3_catch
    function test3() {
        try {
            console.log('test_3_try');
            throw new Error('throw');
        } catch (error) {
            console.log(error.message);
            return 'test_3_catch';
        } finally {
            console.log('test_3_finally');
        }
    }
</script>

</div>

结果

在这里插入图片描述

(若有什么错误,请留言指正,3Q)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值