了解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; (编辑:湖南网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |