开发者

How does Javascript react to errors?

开发者 https://www.devze.com 2023-04-13 02:44 出处:网络
I have been quite 开发者_如何学Pythoncurious about how javascript reacts to errors(like ReferenceError, for example). When it encounters a runtime error, it seems to return from the function that it i

I have been quite 开发者_如何学Pythoncurious about how javascript reacts to errors(like ReferenceError, for example). When it encounters a runtime error, it seems to return from the function that it is called in which, in turn, fails the function it was called in.

Does it consequently fail all the functions in the frame stack? (This is more of a question out of academic curiosity. Hope somebody can explain it to me?)

Thanks!


JavaScript exception handling is much the same as other languages' error handling - it will throw an error up the call stack until handled by the catch of a try block. If there is no try/catch, then the current execution will stop.

All the function calls below the catch will be exited - they won't return anything, and the following lines of code will not be executed.


It continues up the call stack until it reaches a a try...catch block.

You can see a simple example on JSFiddle.


It returns an Object of the error, and like most Objects, it has has methods and properties

try {
    a/1;
} catch(err) {
    console.log(err.name) //ReferenceError
    console.log(err.message); //a is not defined
    console.log(err.constructor); //ReferenceError() { [native code] }
    console.log(err.toString()); //ReferenceError: a is not defined
    console.log(err.stack) 
    /*
      ReferenceError: a is not defined
      at errCatch (<anonymous>:3:11)
      at <anonymous>:1:11
    */
}

note, console.log(Object) is the same as Object.toString(). Hope it helps.

0

精彩评论

暂无评论...
验证码 换一张
取 消