Topic 70 of 87
try / catch
Overview
In JavaScript, if a critical error occurs (like trying to access a property on undefined), the script completely "crashes" and stops executing.
The try...catch statement allows you to test a block of code for errors (try). If an error occurs, the execution immediately jumps to the catch block, preventing the application from crashing and allowing you to handle the error gracefully.
Syntax
Basic Error Handling
javascript
try {
// We attempt to run risky code
const user = JSON.parse("invalid-json-string");
console.log("This line will NEVER run.");
} catch (error) {
// If anything fails in the 'try' block, we land here!
console.error("Oops, parsing failed!");
// The 'error' object contains details about the crash
console.log(error.message);
}Common Pitfalls
- Using
try...catchfor Syntax Errors.try...catchonly catches Runtime Errors (errors that occur while the code is actively running). If you have a missing bracket (Syntax Error), the JS engine won't even compile the code, so thecatchblock cannot save you. - Using
try...catcharound asynchronoussetTimeoutcallbacks. Thetryblock finishes executing immediately, long before the timeout callback runs. If the callback throws an error, thecatchblock will NOT catch it!
Interview Questions
Q:
Can a
try...catch block catch a Syntax Error?A:
No. Syntax errors prevent the code from even compiling or executing. try...catch only handles exceptions that occur during runtime execution.
Real-World Example
Safely attempting to read data from LocalStorage, which can throw errors if the user has disabled cookies/storage in their browser for privacy reasons.
example
javascript
let theme = "light";
try {
theme = localStorage.getItem("theme");
} catch (err) {
console.warn("LocalStorage access denied.");
}Check Your Knowledge
Test your understanding of try / catch with these quick questions.