What is an error ?
An error in any programming language is a mistake that disrupts the normal flow of a program and prevents the code from executing properly. In some cases, errors can even cause the program to crash.
Errors usually occur due to incorrect syntax or logical mistakes in the code. Syntax errors happen when the code does not follow the rules of the programming language, while logical errors occur when the program runs but produces incorrect results because of flawed logic.
Handling errors using try , catch and finally in JS :
In javascript try catch block is used to handle runtime errors.
Runtime errors occurs during the execution of script not when you write the code.
It can cause unexpected crashes.
It cannot catch syntax errors ( like a bracket missing) because the script is not even run at that time.
Try block : Try block contains the code that may introduce errors. If error occurs execution jumps to catch block.
Catch Block : Catch blog only runs when error occur in try block. Catch block has access of error object. This object contains error name (eg. TypeError) and error message etc.
Finally Block : This block always runs after try and catch. Usually used for cleanup.
Example Code :
try {
// Code that may cause an error
let user = null;
console.log(user.name); // Error
}
catch (error) {
// Runs if an error occur
console.log("Error caught:", error.message);
}
finally {
// Always runs
console.log("Execution completed");
}
Synchronous Execution :
It won't catch errors in asynchronous call backs (like setTimeout) unless the try catch code is inside the callback function.
Example Code :
try { setTimeout(() =>
{
throw new Error("Something went wrong!");
}, 1000);
}
catch (err) { console.log("Caught:", err.message); }
Output :
Uncaught Error: Something went wrong!
Catch Block did not run.
Why this happens : Javascript works on event loops.
1. try block runs.
2. setTimeOut schedule back for later.
3. After 1 second callback run separately .
4. Error happens outside the try block.
You must put try catch inside async callback.
Example Code :
setTimeout(() => {
try {
throw new Error("Something went wrong!");
}
catch (err) { console.log("Caught:", err.message); }
}, 1000);
Output :
Caught: Something went wrong!
Async/Await Support :
It works with async/await. Because await stop the execution of code and wait for resolve/reject the promise. If promise reject catch block runs.
async function test() {
try {
await Promise.reject("Error occurred");
}
catch (err) { console.log("Caught:", err); }
}
test();
Output :
Caught : Error occurred
How Try Catch detect and show errors :
When an error occur inside a try block javascript engine automatically creates an Error Object and pass it to catch block. This object contains essential details about failure to handle the error gracefully.
Core Properties of Error Object :
Every built in javascript Error object has at least these three properties.
1. name : A string that specifies the type of error (eg. TypeError , ReferenceError , SyntaxError).
2. message : A human readable string to throw the custom error message.
3.stack : It provide the trace of the function calls. Basically it tells you where error occur and how we reached at that error. It also provides the line number where error make it easy to
debug the code. However, the stack property of Error object is not an official part of ECMAScript specifications. But it is implemented of all major JavaScript engines (v8 , SpiderMonkey , etc).
How to throw custom error messages :
throw new Error () : You can throw user defined exception using throw statement halts the
current process and pass the error object to the nearest catch block.
new Error()→ creates an error objectthrow→ stops execution and sends error to nearestcatch
Example Code :
function withdraw(amount, balance){
if (amount > balance) {
throw new Error("Insufficient balance");
} return balance - amount;
}
try { withdraw(500, 100); }
catch (err) { console.log(err.message); }
Insufficient balance
Built-in Error Types :
throw new TypeError("Wrong type");
throw new ReferenceError("Variable not found");
Top comments (0)