Chapter 4. Error Handling

1.  Trying to read a property from an undefined value, or using a function that does not exists, will cause an error to be signaled.

 

2.  Checking input is always a judgment call—you have to identify the mistakes that are likely to occur and that are likely to have subtle, complicated effects (rather than just causing an error right away).

 

3.  When a function encounters a problem that it cannot solve itself, one possible reaction is to return a value that it could not normally return. It does, however, have its downsides. First, what if the function can already return every possible kind of value? The second issue with returning special values is that it can sometimes lead to a whole lot of clutter. If a piece of code is called 10 times, you have to check 10 times whether the special value was returned.

 

4.  It is possible for code to raise (or throw) an exception, which is a value. Raising an exception somewhat resembles a super-charged return from a function—it does not just jump out of the current function but also out of its callers, all the way up to the top-level call that started the current execution. This is called unwinding the stack. It is possible to set obstacles for exceptions along the stack. These catch the exception as it is zooming down and can do something with it, after which the program continues running at the point where the exception was caught.

 

5.  throw is the keyword that is used to raise an exception. The keyword try sets up an obstacle for exceptions: When the code in the block after it raises an exception, the catch block will be executed. The variable named in parentheses after the word catch will hold the exception value when this block executes. try statements can also be followed by a finally keyword, which means “no matter what happens, run this code after trying to run the code in the try block.” If a function has to clean something up, the cleanup code should usually be put into a finally block.

 

6.  A special type of objects is raised for problems like getting properties from undefined. These always have a message property containing a description of the problem. You can raise similar objects using the new keyword and the Error constructor, giving the message as argument: throw new Error("Wolf!");

你可能感兴趣的:(JavaScript,catch,finally,Exceptin,Error Handling)