我编写简单的Javascript除法函数并进行异常处理
使用throw
,try()
和catch()
问题是代码有异常
根本不工作甚至没有显示
这是我的代码
<html>
<head>
<title>JavaScript lab</title>
<meta charset="utf-8" />
<script language="javascript">
function div(a,b) {
if (b == 0)
throw { name: 'notallowed', message: 'div by zero' };
var c = a/b;
alert(c);
}
}
try {
var x = prompt("Enter num1");
var y = prompt("Enter num2");
div(a,b);
}
catch(e) {
alert("Error: "+e.message);
}
</script>
</head>
</html>
答案 0 :(得分:2)
可能这样可以正常工作
function div(a,b) {
if (b == 0){
throw { name: 'notallowed', message: 'div by zero' };
}
var c = a/b;
alert(c);
}
{
if(b==0)
答案 1 :(得分:1)
//modify
function div(a,b) { //function div(a,b)
if (b == 0){
throw { name: 'notallowed', message: 'div by zero' };
var c = a/b;
alert(c);
}
}
try {
var x = prompt("Enter num1");
var y = prompt("Enter num2");
//modify
div(x,y);//div(a,b);
}
catch(e) {
alert("Error: "+e.message);
}
答案 2 :(得分:1)
这应该有效
function div(a,b) {
if (b == 0) {
throw { name: 'notallowed', message: 'div by zero' };
}
var c = a/b;
alert(c);
}
try {
var x = prompt("Enter num1");
var y = prompt("Enter num2");
div(x,y);
}
catch(e) {
alert("Error: "+e.message);
}