Chapter 11. Exceptions and Error Handling
As much as we would all like to live in an error-free world, we don’t have that luxury. Even the most trivial applications are subject to errors arising from conditions you didn’t anticipate. The first step to writing robust, high-quality software is acknowledging that it will have errors. The second step is anticipating those errors and handling them in a reasonable fashion.
Exception handling is a mechanism that came about to deal with errors in a controlled fashion. It’s called exception handling (as opposed to error handling) because it’s meant to deal with exceptional circumstances—that is, not the errors you anticipate, but the ones you don’t.
The line between anticipated errors and unanticipated errors (exceptions) is a blurry one that is very much situational. An application that is designed to be used by the general, untrained public may anticipate a lot more unpredictable behavior than an application designed to be used by trained users.
An example of an anticipated error is someone providing an invalid email address on a form: people make typos all the time. An unanticipated error might be running out of disk space, or a usually reliable service being unavailable.
The Error Object
JavaScript has a built-in Error
object, which is convenient for any kind of error handling (exceptional or anticipated). When you create an instance of Error
, you can provide an error message:
const
err
=
new
Error
(
'invalid email'
);
Creating an
Get Learning JavaScript, 3rd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.