wiki/content/20201111092905-javascript_exceptions.md

1 KiB

date id title
20201111 44e4d5c4-ea16-4417-a8e8-5036d3fdd370 JavaScript Exceptions

Introduction

JavaScript supports exceptions.

Syntax

function promptDirection(question) {
  let result = prompt(question);
  if (result.toLowerCase() == "left") return "L";
  if (result.toLowerCase() == "right") return "R";
  throw new Error("Invalid direction: " + result);
}

function look() {
  if (promptDirection("Which way?") == "L") {
    return "a house";
  } else {
    return "two angry bears";
  }
}

try {
  console.log("You see", look());
} catch (error) {
  console.log("Something went wrong: " + error);
}

See also