Web browsers are such a hostile environment that it is almost guaranteed that we will constantly deal with runtime errors. Users provide invalid input in ways you didn't think of. New browser versions change their behavior. Ajax calls can fail for any number of reasons.
Many times we cannot prevent runtime errors from happening, but at least we can deal with them in a manner that makes the user experience less traumatic.
Completely unhandled errors
Look at this seemingly trivial code sample:
window object has an event called
error for which we can add an event handler, listening for global errors. The next demo shows an example of this:
try...catch...finally block, also present in many other languages:
The idea is simple. If anything goes wrong in the statements that are inside the
try block's statements then the statements in the
catch block will be executed and the error will be passed in the
error variable. The
finally block is optional and, if present, is always executed last, whether or not an error is caught.
Let's fix our example to catch that error:
It's a good programming practice to only handle the error on the spot if you are certain of what it is and if you actually have a way to take care of it (other than just suppressing it altogether.) To better target our error handling code, we will change it to only handle errors named "TypeError", which is the error name that we have identified for this bug.
We can use the
throw statement to throw our own types of errors. The only recommendation is that our error object also has a
message properties to be consistent with the built-in error handling.
message: 'The given color is not a valid color value.'