JavaScript Try...Catch Statement The try...catch statement allows you to test a block of code for errors. Syntax ------------- try { //Run some code here } catch(err) { //Handle errors here } Note that try...catch is written in lowercase letters. Using uppercase letters will generate a JavaScript error! The code displays a custom (User Friendly) error message informing the user of an error --------- EXAMPLE --------- < html> < head> < script type="text/javascript"> var txt="" function WriteWebDev11() { try { documentttt.writttte("WebDev 11") } catch(err) { txt="An error has occurred on this page.\n\n" txt+="Click OK to continue viewing this page,\n" txt+="or Cancel to return to the home page.\n\n" if(!confirm(txt)) { document.location.href="../" } } } < /script> < /head><body> < input type="button" value="View message" onclick="WriteWebDev11()" /> < /body></html> - - - - - - - - - - - - - - - - - - The throw statement allows you to create an exception. Use this statement together with the try...catch statement The throw statement allows you to control program flow and generate an accurate error messages. Syntax throw(exception) try { if(condition) throw "ErrorName1" else if(condition) throw "ErrorName2" } catch(er) { if(er=="ErrorName1") action if(er=="ErrorName2") action } - - - - - - - - - - - - - - - - - - JavaScript onerror Event The onerror event is fired whenever there is a script error in the page. The onerror event has three arguments: msg (error message), url (the url of the page that caused the error) and line (the line where the error occurred). The value returned by onerror determines whether the browser displays a standard error message. If you return false, the browser displays the standard error message in the JavaScript console. If you return true, the browser does not display the standard error message. Syntax ------------- onerror=handleErr function handleErr(msg,url,l) { //Handle the error here return true or false } ------------- EXAMPLE ------------- < html> < head> < script type="text/javascript"> onerror=handleErr var txt="" function WriteWebDev_11() { documentttt.writttte("WebDev 11") } // Error Catcher function handleErr(msg,url,l) { return true } < /script> < /head><body> < input type="button" value="View message" onclick="WriteWebDev_11()" /> < /body></html> -------------