try...catch block
suggest changetry...catch handles a thrown exception. It does not catch an error passed to a callback or rejected as a promise.
try {
var a = 1;
b++; // this throws because b is undefined
console.log(b); //this line will not be executed
} catch (error) {
console.log(error); //here we handle the error caused in the try block
}
b++ throws, and that exception is passed to catch. The handler can log it, change it, or throw it again.
try {
var a = 1;
b++;
console.log(b);
} catch (error) {
error.message = "b variable is undefined, so the undefined can't be incremented"
throw error;
}
In the above example we modified the message property of error object and then throw the modified error.
You can throw any value in the try block and handle it in catch:
try {
var a = 1;
throw new Error("Some error message");
console.log(a); //this line will not be executed;
} catch (error) {
console.log(error); //will be the above thrown error
}
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents