Exception Handling in JavaScript

Below is the simple code to understand, how to handle the exception using javascript and alert to user.

<script language="javascript" type="text/javascript">
        window.onload = intAll;
        function intAll(){
            var ans = window.prompt("Enter a number","");
            try{
                if (isNaN(ans) || ans < 0)
                    throw new Error("Invalid Number");
                else    
                    alert("Square root of the number " + ans + " is " + Math.sqrt(ans));
            }
            catch (err){
                alert(err.message);
            }
        } 
</script>
Advertisements

#error-handling