| [ Web Proxy ] |
| Viewing: https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Statements/throw | [Back] [Original] |
Get to know MDN better
This page was translated from English by the community. Learn more and join the MDN Web Docs community.
This feature is well established and works across many devices and browser versions. Its been available across browsers since 2015 7.
throw (throw) . (throw
.), catch
. catch .
function getRectArea(width, height) {
if (isNaN(width) || isNaN(height)) {
throw new Error("Parameter is not a number!");
}
}
try {
getRectArea(3, "A");
} catch (e) {
console.error(e);
// Expected output: Error: Parameter is not a number!
}
throw expression;
throw . expression .
:
throw "Error2"; // .
throw 42; // 42 .
throw true; // true .
. catch .
UserException throw .
function UserException(message) {
this.message = message;
this.name = "UserException";
}
function getMonthName(mo) {
mo = mo - 1; // .(1 = 1, 12 = 12)
var months = [
"Jan",
"Feb",
"Mar",
"Apr",
"May",
"Jun",
"Jul",
"Aug",
"Sep",
"Oct",
"Nov",
"Dec",
];
if (months[mo] !== undefined) {
return months[mo];
} else {
throw new UserException("InvalidMonthNo");
}
}
try {
// try
var myMonth = 15; // 15
var monthName = getMonthName(myMonth);
} catch (e) {
monthName = "unknown";
console.error(e.message, e.name); //
}
.
throw ZipCodeFormatException .
/*
* ZipCode .
*
* :
* 12345
* 12345-6789
* 123456789
* 12345 6789
*
* ZipCode ,
* .
*/
function ZipCode(zip) {
zip = new String(zip);
pattern = /[0-9]{5}([- ]?[0-9]{4})?/;
if (pattern.test(zip)) {
// .
this.value = zip.match(pattern)[0];
this.valueOf = function () {
return this.value;
};
this.toString = function () {
return String(this.value);
};
} else {
throw new ZipCodeFormatException(zip);
}
}
function ZipCodeFormatException(value) {
this.value = value;
this.message = "does not conform to the expected format for a zip code";
this.toString = function () {
return this.value + this.message;
};
}
/*
*
* .
*/
const ZIPCODE_INVALID = -1;
const ZIPCODE_UNKNOWN_ERROR = -2;
function verifyZipCode(z) {
try {
z = new ZipCode(z);
} catch (e) {
if (e instanceof ZipCodeFormatException) {
return ZIPCODE_INVALID;
} else {
return ZIPCODE_UNKNOWN_ERROR;
}
}
return z;
}
a = verifyZipCode(95060); // 95060
b = verifyZipCode(9560); // -1
c = verifyZipCode("a"); // -1
d = verifyZipCode("95060"); // 95060
e = verifyZipCode("95060 1234"); // 95060 1234
throw (catch) .
50 .
try {
throw n; // .
} catch (e) {
if (e <= 50) {
// 1-50
} else {
// ,
throw e;
}
}
| Specification |
|---|
| ECMAScript 2027 LanguageSpecification # sec-throw-statement |
This page was last modified on 2026 7 15 by MDN contributors.
Your blueprint for a better internet.
Portions of this content are 19982026 by individual mozilla.org contributors. Content available under a Creative Commons license.
| Web Proxy Viewer | New URL | Original Page |