Today you will learn:
try...catch blocksBy the end, you will be able to catch errors and debug code effectively.
Use try...catch to safely handle errors:
try {
JSON.parse("invalid");
} catch (error) {
console.log("Error caught!");
}
Explanation:
try block contains code that might throw an errorcatch block runs if an error occursUse browser developer tools to debug:
console.log() to inspect variables
try {
JSON.parse("invalid");
} catch (error) {
console.log("Error caught!");
}
Write code that handles an error safely:
function safeParse(json) {
try {
return JSON.parse(json);
} catch (error) {
console.log("Invalid JSON:", error.message);
return null;
}
}
// Example usage
const data = safeParse('{"name": "John"}');
const badData = safeParse("invalid");