HTML5 Series - Error Handling
One thing you can say for certain about writing code is at some point your going to write something that error's. It may be picked up in code reviews, or by a tester, and then fixed but for certain as you are human at some point you will make a mistake. What's important though is what happens after the mistake.
If your a C# developer then good news JavaScript has the same try, catch, finally functionality that C# has and it works in the same way.
Wrap you code that could error with a try statement and curly braces and following it add in a catch statement with the code that you want to execute in the event of an error. Finally if you want some code to execute either way after both, place this in the finally block.
1try2{3 functionThatDoesntExists();4}5catch (err)6{7 alert(err.message);8}9finally10{11 //Code to execute at the end12}
Notice the catch section is passed a parameter and I am then alerting a property of this called message. The error parameter can be useful for debugging what actually went wrong and contains a few other parameters.
- Description
- Message
- Name
- Number
- Stack
Sometimes you may also want to cause an error to be thrown. You may be asking why, but consider people calling your functions may in-fact pass values that are not valid. You could detect this and throw an error containing some useful information before there incorrect parameter values causes your code to error and a less helpful message given.
1var err = new Error(1, "Oh dear, that's not going to work"); // First parameter is the error number, second is the message2throw err;