JavaScript_异常

try 语句测试代码块的错误。
catch 捕捉try中出现的错误
throw 抛出异常(异常可以是 JavaScript 字符串、数字、逻辑值或对象)

<html>
<head>
    <script>
    function test(){
        try{
            alertt("lalala");
        }
        catch(err){
            alert("捕捉到异常");
        }
    }
    </script>
</head>

<body>
    <button onclick="test()">测试异常</button>
</body>
</html>

try中的alert出现拼写错误,于是在catch中捕捉到异常并执行catch中的代码

<!DOCTYPE html>
<html>
<body>
    <script>
    function aaa(){
        try{        
            var s=document.getElementById("input").value;
            if (isNaN(s)) throw "请输入数字(NaN)";
            else if (s == ""|| s==null) throw "请输入值(null)";
            else if(s>10) throw "大了";
            else  throw "小了";
        }
        catch(err){
            var result = document.getElementById("result");
            result.innerHTML = err;
        }
    }
    </script>
        <p>input a num:</p>
        <input type="text" id="input">
        <button onclick="aaa()">test2</button>
        <p id="result"></p>
</body>
</html>

catch捕捉异常err(类似一个var变量),捕捉过后的err的用法类似一个变量。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值