A runtime error is an error that occurs while a program is being executed. A runtime error can be the result of invalid user input, a browser change, or bad data sent from the server.
It is the programmer's job to anticipate, "catch," and "handle" potential runtime errors..
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 then the statements in the
catch block will be executed. The
finally block is optional and, if present, is always executed last, whether or not an error is caught.
The finally Block
finally block except for advanced code involving nested try / catch blocks.
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 errors. While there are several ways to do this, a simple way is to throw a new
throw new Error('The given color is not a valid color value.');