JavaScript-中级:8 JavaScript的异常处理

1.正常的异常处理

ps:finally是一定会被执行的。

2.自定义抛出错误

参考代码(上述1和2):

<!DOCTYPE html>
<html 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>js异常处理</title>
</head>
<body>
    <script>
    // 1.异常处理流程
    try {
        console.log(1); // 1
        var t = new jsf(); // 出异常语句,此处jsf未定义
        console.log(2); // 未执行
    } catch (e) {
        console.dir(e)  // ReferenceError: "jsf is not defined"
                        // <anonymous> file:///C:/Users/lisa/Documents/My/Learn_CodeTych/Vscode/JavaScript/learn_16_exeception.html:13

        console.log(e.message); // jsf is not defined
   } finally{
        console.log("finally"); // finally  (一定会被执行)
    }

    // alert('2333');
    console.log(3); // 3

    // 2.抛出异常
    function add(a, b){
        if(typeof(a) != "number"){
            throw "传入参数不是整数类型";  // 只要遇到throw,程序就停止,代码立即跳转到catch语句,如果没有catch语句,当前js程序就会结束。
        }
        return a + b;
    }
    // var res = add('ad', 44); // 报错:uncaught exception: 传入参数不是整数类型
    // console.log(2.1) // 未执行

    try {
        var res2 = add("asd", 2); // 将代码放在try catch中。
    } catch (e) {
        // 打印错误信息
        console.log(e); // 传入参数不是整数类型  (由于是自己定义的,故这里直接用e,因为系统抛出的异常里,message里存的是异常信息,故捕获系统抛出的异常要用e.message)
    }
    console.log(2.2) // 2.2
    </script>
</body>
</html>

3.错误信息对象Error

ps:catch中可以根据错误类型不同,做相关处理,不过浏览器不同兼容不好。

(略)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值