了解JavaScript错误的原理
一、JavaScript try ... catch语句
try语句允许定义一个代码块,该代码块在执行时将进行错误测试,catch如果try块中发生错误,则该语句允许您定义要执行的代码块。 JavaScript语句try和catch成对出现。 try { //try_statements-尝试尝试的语句 }catch(err){ //catch_statements-处理错误的语句 } 完整代码: 例中,将“alert”写为“aaalert”来故意产生错误。 <!DOCTYPE html> <html> <title>项目</title>
<body style="background-color: aqua;"> <h1>JavaScript Error</h1>
<p>将" alert"写为" aaalert"来故意产生错误:</p>
<p id="result"></p> <script> try { aaalert("Hello world"); } catch (e) { document.getElementById("result").innerHTML = e.name + "<br>" + e.message; } </script>
</body> </html> 将" alert"写为" aaalert"来故意产生错误: 发生错误时,JavaScript通常会停止运行,并创建一个具有两个属性的Error对象:name和message。 二、JavaScript throw语句throw语句引发用户定义的异常。 throw语句允许您创建自定义错误。从技术上讲,这称为“引发异常 ”。异常可以是JavaScript字符串,数字,布尔值或对象。 throw "Invalid"; // 生成带有字符串值的异常 throw 32; // 生成值为32的异常 throw true; // 生成值为true的异常 如果throw与try和一起使用catch,则可以指定程序流程并生成自定义错误消息。 在例中,如果传递任何非数字参数,则getRectArea()将引发自定义错误: <script> function getRectArea(width, height) { if (isNaN(width) || isNaN(height)) { throw "参数不是数字!"; } }
try { getRectArea(5, 'Z'); } catch(err) { document.getElementById('para').innerHTML = err; } </script> 1. 输入验证如果值错误,则引发异常(err)。catch语句捕获异常(err),并显示自定义错误消息。 var x = document.querySelector("input").value; try { if(x == "") throw "is Empty"; if(isNaN(x)) throw "Not a Number"; if(x > 10) throw "too High"; if(x < 5)throw "too Low"; } catch(err) { document.getElementById("para").innerHTML = "Input " + err; (编辑:晋中站长网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |