try { //在这里运行代码 throw } catch(err) { //在这里处理错误 }
实验案例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<script type="text/javascript">
function myfunction(){
try{
var xx=document.getElementById("box").value;
if(xx==''){
throw'不能为空';
}
if(xx>10){
throw'输入错误';
}
if(xx<5){
throw'输入值太小了';
}
}
catch(err){
var yy=document.getElementById("mess");
yy.innerHTML='error:'+err+'.';
}
}
</script>
</head>
<body>
<p>输入一个5到10的数</p>
<input type="text" id="box" >
<button οnclick="myfunction()">点击</button>
<p id="mess"></p>
</body>
</html>