Handling Errors
Errors are a normal part of application execution. They occur when a non-happy path is encountered, such as:
- Data received from an API is malformed.
- The connection to a database is lost.
- A user attempts to log in with an incorrect password.
When an error is thrown in JavaScript, the runtime immediately aborts the current execution path. If the error is not caught, it crashes the entire program.
const user = {};
// This throws a TypeError because user.profile is undefined
console.log(user.profile.age);
// This line is NEVER reached because the program crashes
console.log("Operation Complete");
The try/catch Block
To prevent the program from crashing, you can wrap potentially dangerous code inside a try/catch block.
If an error is thrown anywhere inside the try block, execution immediately jumps into the catch block. The program then continues running normally afterwards.
try {
const user = {};
// This throws an error
console.log(user.profile.age);
// This is skipped
console.log("Age printed successfully.");
} catch (err) {
// We capture the error object and log its message gracefully
console.log("An error occurred:", err.message);
}
// The program survives and reaches this line
console.log("Operation Complete");
Practical Example
A common pattern is wrapping dangerous network requests or data lookups.
function main() {
try {
const record = getDatabaseRecord(99);
console.log("Record found:", record);
} catch (err) {
console.log("Failed to fetch record:", err.message);
}
}