Abdulrhman.Z
Abdulrhman.Z

Reputation: 53

simple exception in javascript cause the codeto not work

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

Answers (3)

sunysen
sunysen

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

BigMike
BigMike

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

Naveen Kumar Alone
Naveen Kumar Alone

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

Related Questions