码迷,mamicode.com
首页 > 编程语言 > 详细

JavaScript 错误 - throw、try 和 catch

时间:2017-06-14 11:35:58      阅读:126      评论:0      收藏:0      [点我收藏+]

标签:put   func   text   cli   ==   int   type   get   错误信息   

try 语句测试代码块的错误。

catch 语句处理错误。

throw 语句创建自定义错误。(就是自己希望显示的错误信息)

<body>

?

<p>请输出一个 510 之间的数字:</p>

?

<input id="demo" type="text">

<button type="button" onclick="myFunction()">测试输入</button>

<p id="message"></p>

?

<script>

function myFunction() {

    var message, x;

    message = document.getElementById("message");

    message.innerHTML = "";

    x = document.getElementById("demo").value;

    try { 

        if(x == "")  throw "值为空soyo";

        if(isNaN(x)) throw "不是数字";

        x = Number(x);

        if(x < 5)    throw "太小";

        if(x > 10)   throw "太大";

    }

    catch(err) {

        message.innerHTML = "错误: " + err;

    }

}

</script>

?

</body>

 

JavaScript 错误 - throw、try 和 catch

标签:put   func   text   cli   ==   int   type   get   错误信息   

原文地址:http://www.cnblogs.com/soyo/p/7007582.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!