Write a try/catch block that attempts to parse a JSON string. If parsing fails, log "Invalid JSON" to the console.
Errors can occur during code execution. The try...catch
statement lets you handle these errors gracefully without breaking your program.
try {
// Code that might throw an error
let result = riskyFunction();
console.log(result);
} catch (error) {
// Handle the error
console.error("An error occurred:", error.message);
}
try {
// Code that might throw
} catch (e) {
console.error(e);
} finally {
console.log("This runs regardless of error");
}