Error Handling Patterns
try and catch
Handle a parsing failure with a fallback label.
try and catch
try_catch_parse.js
const text = "42";
let label = "";
try {
const value = Number(text);
if (Number.isNaN(value)) {
throw new Error("not numeric");
}
label = "value:" + value;
} catch (error) {
label = "fallback";
}
console.log("text=" + text);
console.log("label=" + label);
try-catch-parse
`try` runs code that may fail. `catch` handles the failure and lets the program continue with a fallback value.