Try...Catch statements are used to handle runtime errors. When an error occurs, they let you handle it gracefully instead of crashing the program.
🛡️ Structure:
• try {}: Code that might fail
• catch(error) {}: Handle errors
• finally {}: Always runs
javascript
// Basic try-catch
try {
const result = 10 / 0;
console.log(result); // Infinity (not error in JS)
// This will cause error
const x = y + 5; // y is not defined
} catch (error) {
console.log(`Error caught: ${error.message}`);
}
// Try-catch with finally
function divideNumbers(a, b) {
try {
if (b === 0) {
throw new Error("Cannot divide by zero");
}
return a / b;
} catch (error) {
console.log(`Error: ${error.message}`);
return null;
} finally {
console.log("Division operation completed");
}
}
console.log(`Result: ${divideNumbers(10, 2)}`);
divideNumbers(10, 0);
// Catching specific errors
try {
JSON.parse("invalid json");
} catch (error) {
if (error instanceof SyntaxError) {
console.log("Invalid JSON format");
}
}You should see
Error caught: y is not defined Result: 5 Division operation completed Error: Cannot divide by zero Division operation completed Invalid JSON format