Saturday, March 3, 2018

demonstrate exception handling in java script

To create an html page to demonstrate exception handling in javascript, Create an html page named as ―exception.html and do the following.
i. within the script tag write code to handle exception
a) define a method RunTest() to get any string values(str) from the user and call the method Areletters(str).
b) In Areletters(str) method check whether str contain only alphabets (a-z, AZ), if not throw exception.

c) Define a exception method Input Exception(str) to handle the exception thrown by the above method.


<!DOCTYPE html>
<html>
<body  >

<p >Click the button to demonstrate Exception handling </p>

<button  onclick="RunTest()" >Touch me</button>

<p id="message"></p>

<script>
 function isalpha(str) {
var f=0;
for(i=0;i<str.length;i++)
   {
            if (((str[i] >= 'a') && (str[i] <= 'z')) || ((str[i] >= 'A') && (str[i] <= 'Z')))
               f=0;
            else
            f=1;
}
if (f==0)
return 1;
else
return 0;
  }
function RunTest() {
    var str = prompt("Please enter any string", "sambasiva");



try {
        if(str == "") throw "is empty";
      else if(!isalpha(str)) throw "string must contain alphabets only";
       else
          document.getElementById("message").innerHTML =
        "Entered string: " + str;

    }

    catch(err) {
        document.getElementById("message").innerHTML = "Error: " + err + ".";
    }

 
}
</script>

</body>
</html>

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home