Handle a parsing failure with a fallback label.

try-catch-parse `try` runs code that may fail. `catch` handles the failure and lets the program continue with a fallback value.

try and catch

text
try_catch_parse.js
Replay: real traced execution (multi-file project)
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);
const text = "7";
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);
const text = "bad";
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);
  1. text ← 42, label ← (empty)

    1const text→ 42 = "42"; //@text="7", "bad"2let label→ (empty) = "";
  2. value ← 42, label ← value:42

    1const text = "42"; //@text="7", "bad"2let label = "";34try {5  const value→ 42 = Number(text42);6  if (Number.isNaN(value)) {7    throw new Error("not numeric");8  }9  label = "value:" + value42;10} catch (error) {
    values this stepvalue:42label
  3. console.log("text=" + text);

    11  label = "fallback";12}1314console.log("text=" + text42);15console.log("label=" + labelvalue:42);
    outputtext=42
    label=value:42
  1. text ← 7, label ← (empty)

    1const text→ 7 = "7";2let label→ (empty) = "";
  2. value ← 7, label ← value:7

    1const text = "7";2let label = "";34try {5  const value→ 7 = Number(text7);6  if (Number.isNaN(value)) {7    throw new Error("not numeric");8  }9  label = "value:" + value7;10} catch (error) {
    values this stepvalue:7label
  3. console.log("text=" + text);

    11  label = "fallback";12}1314console.log("text=" + text7);15console.log("label=" + labelvalue:7);
    outputtext=7
    label=value:7
  1. text ← bad, label ← (empty)

    1const text→ bad = "bad";2let label→ (empty) = "";
  2. value ← NaN

    1const text = "bad";2let label = "";34try {5  const value→ NaN = Number(textbad);6  if (Number.isNaN(value)) {
  3. if (Number.isNaN(value))

    4try {5  const value = Number(text);6  if (Number.isNaN(valueNaN)) {7    throw new Error("not numeric");8  }
  4. label ← fallback

    9  label = "value:" + value;10} catch (error) {11  label = "fallback";12}
    values this stepfallbacklabel
  5. console.log("text=" + text);

    11  label = "fallback";12}1314console.log("text=" + textbad);15console.log("label=" + labelfallback);
    outputtext=bad
    label=fallback