Handling error by try & catch in different browsers

While executing Javascript code some time the script may develop some error and an un-wanted ugly message gets posted to the viewer. This message gets displayed in Tools > Error console of firefox browser and in internet explorer it get displayed through a new window. In IE it says about run time error and ask us to debug or not. As a programmer it may help us but such messages results in poor user experience. How to suppress error messages in JavaScript ? We can prevent this window displaying by handling the error and its associated message.

JavaScript has exception handling by using try catch functions. We can keep our code block inside try and pass all the error to catch block. Here is a sample code on try and catch.

Note that we have not defined the variable my_sum and try to print the value by using document.write. For your learning we have defined the variable and commented this line , you can uncomment and check the difference.
<script type="text/javascript">
<!--
try
{
//var my_sum=5;
document.write("The sum of 2 and 3 = " + my_sum);
}
catch(err)
{
document.write("There is an error Sorry");
document.write("<br>...You can continue with rest of the page...<br>");

}
//-->
</script>
We can display the error message which has caused the exception by error object. Here internet explorer and firefox behaves differently so we have to identify the browsers and then display the message accordingly through an alert box.
<script type="text/javascript">
<!--
try
{
//var my_sum=5;
document.write("The sum of 2 and 3 = " + my_sum);
}
catch(err)
{
document.write("There is an error Sorry");

if(navigator.userAgent.indexOf("Firefox")!=-1){
var msg=err;
}
else if (navigator.appName.indexOf("Internet Explorer")!=-1){
var msg=err.description;
}

alert(msg);

}
//-->
</script>
Your Rating





Post your comments , suggestion , error , requirements etc here .




We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
©2000-2019 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer