[ Web Proxy ]
URL:
Viewing: https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Statements/throw [Back]  [Original]

throw - JavaScript | MDN

MDN Web Docs

View in English Always switch to English

throw

Baseline

20157

throw throw catch catch

function getRectArea(width, height) {
  if (isNaN(width) || isNaN(height)) {
    throw new Error("!");
  }
}

try {
  getRectArea(3, "A");
} catch (e) {
  console.error(e);
  // : Error: !
}

js
throw expression;
expression

throw

throw

js
throw error; // catch 
throw new Error("Required"); //  Error 

Error RangeError Error message Web API Error.prototype DOMException

throw

js
throw
new Error();

(ASI)

js
throw;
new Error();

return throw

ASI

js
throw (
  new Error()
);

TypeError

js
function isNumeric(x) {
  return ["number", "bigint"].includes(typeof x);
}

function sum(...values) {
  if (!values.every(isNumeric)) {
    throw new TypeError("");
  }
  return values.reduce((a, b) => a + b);
}

console.log(sum(1, 2, 3)); // 6
try {
  sum("1", "2");
} catch (e) {
  console.error(e); // TypeError: Can only add numbers
}

js
readFile("foo.txt", (err, data) => {
  if (err) {
    throw err;
  }
  console.log(data);
});

(a) readFile (b) Promise()

js
function readFilePromise(path) {
  return new Promise((resolve, reject) => {
    readFile(path, (err, data) => {
      if (err) {
        reject(err);
      }
      resolve(data);
    });
  });
}

try {
  const data = await readFilePromise("foo.txt");
  console.log(data);
} catch (err) {
  console.error(err);
}

ECMAScript 2027 LanguageSpecification
# sec-throw-statement


Web Proxy Viewer  |  New URL  |  Original Page