JS中错误处理(2)

throw语句
使用throw语句可以生成一个例外(exception)。结合 try…catch 使用throw语句可以控制程序流程,并生成准确地出错信息。
语法
throw(exception)
其中exception可以是字符串,整数,布尔值,或一个对象。
注意 throw 为小写字母。 使用大写字母会造成 JavaScript 出错!
例1
以下例子根据变量x的值进行不同的动作。 如果x值大于10或小于0,就会抛出一个错误。出错会被 catch 参数捕获,显示适当的出错信息:

<html> 
<head> 
<script type="text/javascript"> 
onerror
=handleErr 
var txt="" 
function handleErr(msg,url,l) 

txt
="There was an error on this page.\n\n" 
txt
+="Error: " + msg + "\n" 
txt
+="URL: " + url + "\n" 
txt
+="Line: " + l + "\n\n" 
txt
+="Click OK to continue.\n\n" 
alert(txt) 
return true 
}
function message() 

adddlert(
"Welcome guest!"

</script> 
</head><body> 
<input type="button" value="View message" onclick="message()" /> 
</body> 

</html> 
原文地址:https://www.cnblogs.com/ucetgg/p/1384429.html