|
定义和用法
try/catch/finally 语句用于处理代码中可能出现的错误信息。 错误可能是语法错误,通常是程序员造成的编码错误或错别字。也 可能是拼写错误或语言中缺少的功能(可能由于浏览器差异)。 try语句允许我们定义在执行时进行错误测试的代码块。 catch 语句允许我们定义当 try 代码块发生错误时,所执行的代码块。 finally 语句在 try 和 catch 之后无论有无异常都会执行。 注意: catch 和 finally 语句都是可选的,但你在使用 try 语句时必须至少使用一个。 提示: 当错误发生时, JavaScript 会停止执行,并生成一个错误信息。使用 throw 语句 来创建自定义消息(抛出异常)。如果你将 throw 和 try 、 catch一起使用,就可以控制程序输出的错误信息。 示例: function myFunction() {
var message, x;
message = document.getElementById("message");
message.innerHTML = "";
x = document.getElementById("demo").value;
try {
if(x == "") throw "为空";
if(isNaN(x)) throw "不是一个数字";
if(x > 10) throw "太大";
if(x < 5) throw "太小";
}
catch(err) {
message.innerHTML = "输入的值 " + err;
}
finally {
document.getElementById("demo").value = "";
}
}Throw 语句 throw 语句允许我们创建自定义错误。 正确的技术术语是:创建或抛出异常(exception)。 如果把 throw 与 try 和 catch 一起使用,那么您能够控制程序流,并生成自定义的错误消息。 <script>
function myFunction()
{
try
{
var x=document.getElementById("demo").value;
if(x=="") throw "empty";
if(isNaN(x)) throw "not a number";
if(x>10) throw "too high";
if(x<5) throw "too low";
}
catch(err)
{
var y=document.getElementById("mess");
y.innerHTML="Error: " + err + ".";
}
}
</script>
<h1>My First JavaScript</h1>
<p>Please input a number between 5 and 10:</p>
<input id="demo" type="text">
<button type="button" onclick="myFunction()">Test Input</button>
<p id="mess"></p>参考:http://www.runoob.com/jsref/jsref-try-catch.html http://www.w3school.com.cn/js/js_errors.asp 扩展:https://www.cnblogs.com/yangheng/p/6018224.html |
|
|