LEARNING JAVASCRIPT - Trang 193

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 acknowl‐

edging that it will have errors. The second step is anticipating those errors and han‐

dling 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 han‐

dling (exceptional or anticipated). When you create an instance of

Error

, you can

provide an error message:

const

err

=

new

Error

(

'invalid email'

);

Creating an

Error

instance doesn’t, by itself, do anything. What it does is give you

something that can be used to communicate errors. Imagine a function that validates

169

Liên Kết Chia Sẽ

** Đây là liên kết chia sẻ bới cộng đồng người dùng, chúng tôi không chịu trách nhiệm gì về nội dung của các thông tin này. Nếu có liên kết nào không phù hợp xin hãy báo cho admin.