Error Handling (try-catch)
Errors can halt code execution unexpectedly. Managing errors using try-catch blocks keeps your applications running robustly.
1 Try-Catch-Finally flow control
Error statements handle exceptions safely:
- try: Wraps code blocks that may throw exceptions.
- catch: Intercepts and handles errors if they occur, preventing application crashes.
- finally: Executes cleanup code after try/catch, regardless of whether an error was thrown.
- throw: Manually raises custom exceptions using `throw new Error("Message")`.
2 Exception Interception Code
Let's run a program throwing exceptions, trapping them in try-catch, and printing validation warnings:
JavaScript — Exception Handling
▶ Run Code
function parseAge(age) {
if (age < 0) {
throw new Error("Age cannot be negative.");
}
return `Age verified: ${age}`;
}
try {
console.log(parseAge(25));
// Try passing invalid input
console.log(parseAge(-5));
} catch (e) {
console.log("Exception caught: " + e.message);
} finally {
console.log("Validation checklist finished.");
}
console.log("Application continues running smoothly...");
3 Code Challenge
Challenge: Write a function that accepts a JSON string and parses it using `JSON.parse`. Wrap this parsing operation in a try-catch block to handle invalid JSON syntax strings gracefully, and print a custom error message if parsing fails.