JavaScript中的try..catch示例

try … catch示例

function foo(num) {
    // 检查传入的参数是否为数值
    if (typeof num !== "Number") {
        throw {
            type: "Value error",
            info: "The value is not right, it should be a number!"
        };
    } else {
        return num;
    }
}

function testMethod() {
    try {
        foo("fine"); //=> 传入一个非数字字面量,使函数触发异常
    } catch (e) {
        console.log(e.type + ":" + e.info);
        return false //=> 并不会作为返回值
        console.log("here") //=> 这里的代码不会执行
    } finally {
        return true; //=> 作为最终返回值
    }
}

console.log(testMethod()); //=> true


function testMethodTwo() {
    try {
        foo("hello") //=> 触发函数的异常
    } catch (e) {
        console.log("here is catch clause.");
        throw e;  //=> 被finally覆盖,且这里这条语句会被挂起,直到finally子句执行完毕
    } finally {
        return true; //=> 函数最终依然返回true值
    }
}

console.log(testMethodTwo());    //=> 调用函数
console.log("here is ending!");  //=> 这里的语句依然能正常被执行
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值