1. The Basics of try/catch
try/catch
lets you handle errors gracefully instead of letting your program crash.
Syntax:
try {
// Code that might throw an error
} catch (error) {
// Code to handle the error
} finally {
// Optional: code that runs regardless of error
}
try
: The block where you place code that may fail.catch
: Runs if an error occurs in thetry
block. Receives anerror
object.finally
(optional): Runs always, whether an error occurred or not. Useful for cleanup.
2. Example: Basic try/catch
try {
let result = riskyOperation(); // might throw an error
console.log("Operation succeeded:", result);
} catch (error) {
console.log("An error occurred:", error.message);
} finally {
console.log("This runs no matter what.");
}
3. Throwing Your Own Errors
You can use throw
to raise a custom error:
function divide(a, b) {
if (b === 0) {
throw new Error("Cannot divide by zero!");
}
return a / b;
}
try {
console.log(divide(10, 0));
} catch (error) {
console.log("Error:", error.message);
}
Output:
Error: Cannot divide by zero!
4. Catching Specific Errors
You can check the type or message of the error inside catch
:
try {
JSON.parse("invalid json");
} catch (error) {
if (error instanceof SyntaxError) {
console.log("JSON syntax error!");
} else {
console.log("Some other error:", error.message);
}
}
5. Best Practices
- Only wrap risky code in
try/catch
to avoid hiding bugs. - Log or handle errors properly, don’t silently ignore them.
- Use
finally
for cleanup, e.g., closing a file, stopping a loader, or freeing resources. - Use custom error messages to make debugging easier.