Who knows about try... catch statement? Who use it?
So, why not use the try... catch statement?
IntroductionThe mentioned statement is very easy to use. I believe that in most cases it is just a matter of being lazy and developers don't want to waste time adding a few more lines to their functions. I must admit I am lazy too in this matter, but I keep forcing myself to try and catch everytime I can.
The logic behind the statement is simple: whenever you have a function or a block of code, you should put a try block containing the snippet and a catch block that actually contains the code to be run in case of errors.
The only thing you must remember is that you have to write the try... catch statement in lowercase, otherwise it will throw a syntax error... and you don't want that to happen!
// handle the thrown error
ExamplesNow, let's see an example. We write a function opening an alert box, but with an error in it, just to see the effect.
As you may have noticed, there's a syntax error in our show_alert function. Specifically the alert command has too many a ( aaaaalert("Welcome guest!"); ).
error_msg="There was an error on this page.\n\n";
error_msg+="Error description: " + err.description + "\n\n";
error_msg+="Click OK to continue.\n\n";
<input type="button" value="Click me!" onclick="show_alert()" />
Let's see it in action.
Ok! If you click the button, you will see an alert box stating there was an error.
Just change the catch(err) block with the above code. And that's it!
error_msg ="There was an error on this page.\n\n";
error_msg +="Click OK to continue viewing this page,\n";
error_msg+="or Cancel to return to the home page.\n\n";