LEARNING JAVASCRIPT - Trang 198

}

finally

{

console

.

log

(

"...always executed"

);

console

.

log

(

"perform cleanup here"

);

}

Try this example with and without the

throw

statement; you will see that the

finally

block is executed in either case.

Let Exceptions Be Exceptional

Now that you know what exception handling is and how to do it, you might be

tempted to use it for all of your error handling—both the common errors you antici‐

pate, and the errors that you don’t. Throwing an error is, after all, extremely easy, and

it’s a convenient way to “give up” when you encounter a condition that you don’t

know how to handle. But exception handling comes at a cost. In addition to the risk

of the exception never being caught (thereby crashing your program), exceptions

carry a certain computational cost. Because exceptions have to “unwind” the stack

trace until a

catch

block is encountered, the JavaScript interpreter has to do extra

housekeeping. With ever-increasing computer speeds, this becomes less and less of a

concern, but throwing exceptions in frequently used execution paths can cause a per‐

formance issue.
Remember that every time you throw an exception, you have to catch it (unless you

want your program to crash). You can’t get something for nothing. It’s best to leave

exceptions as a last line of defense, for handling the exceptional errors you can’t antic‐

ipate, and to manage anticipated errors with control flow statements.

174 | Chapter 11: Exceptions and Error Handling

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.