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

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s