Reputation: 53
I write simple Javascript division function and doing exception handling
using throw
, try()
and catch()
the problem is that the code with exception
not work at all even prompt not shown
here is my code
<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>
Upvotes: 0
Views: 66
Reputation: 2351
//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);
}
Upvotes: 1
Reputation: 6873
This should work
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);
}
Upvotes: 1
Reputation: 7668
May be this could be works fine
function div(a,b) {
if (b == 0){
throw { name: 'notallowed', message: 'div by zero' };
}
var c = a/b;
alert(c);
}
You have missed a {
at the end of if(b==0)
Upvotes: 2