--- title: throw slug: Web/JavaScript/Reference/Statements/throw translation_of: Web/JavaScript/Reference/Statements/throw ---
throw
문은 사용자 정의 예외를 던질 수 있습니다. 현재 함수의 실행이 중지되고 (throw
이후의 명령문은 실행되지 않습니다.), 컨트롤은 콜 스택의 첫 번째 catch
블록으로 전달됩니다. 호출자 함수 사이에 catch
블록이 없으면 프로그램이 종료됩니다.
throw expression;
expression
예외를 발생하기 위해 throw
문을 사용하세요.
예외를 던지면 expression
은 예외 값을 지정합니다.
다음 각각은 예외를 던집니다:
throw 'Error2'; // generates an exception with a string value throw 42; // generates an exception with the value 42 throw true; // generates an exception with the value true
또한 throw
문은 자동 세미콜론 삽입 (ASI)에 의해 영향을 받으며 throw
키워드와 표현식 사이에 줄 종결자는 허용되지 않으므로 주의해야합니다.
예외를 던질 때 객체를 지정할 수 있습니다. 그러면 catch
블록에서 객체의 속성을 참조 할 수 있습니다.
다음 예제에서는 UserException
유형의 객체를 만들고 throw
구문에서 이 객체를 사용합니다.
function UserException(message) { this.message = message; this.name = 'UserException'; } function getMonthName(mo) { mo = mo - 1; // Adjust month number for array index (1 = Jan, 12 = Dec) 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 { // statements to try var myMonth = 15; // 15 is out of bound to raise the exception var monthName = getMonthName(myMonth); } catch (e) { monthName = 'unknown'; console.log(e.message, e.name); // pass exception object to err handler }
다음 예제는 입력 문자열에서 미국 우편 번호를 테스트합니다.
우편 번호가 잘못된 형식을 사용하는 경우 throw 문은 ZipCodeFormatException
유형의 개체를 만들어 예외를 던집니다.
/* * Creates a ZipCode object. * * Accepted formats for a zip code are: * 12345 * 12345-6789 * 123456789 * 12345 6789 * * If the argument passed to the ZipCode constructor does not * conform to one of these patterns, an exception is thrown. */ function ZipCode(zip) { zip = new String(zip); pattern = /[0-9]{5}([- ]?[0-9]{4})?/; if (pattern.test(zip)) { // zip code value will be the first match in the string 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; }; } /* * This could be in a script that validates address data * for US addresses. */ 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); // returns 95060 b = verifyZipCode(9560); // returns -1 c = verifyZipCode('a'); // returns -1 d = verifyZipCode('95060'); // returns 95060 e = verifyZipCode('95060 1234'); // returns 95060 1234
throw
를 사용하여 예외를 잡은 후에 예외를 다시 던질 수 있습니다.
다음 예제에서는 숫자 값으로 예외를 잡고 값이 50 이상이면 예외를 다시 throw합니다.
반환 된 예외는 둘러싸는 함수 또는 최상위 수준으로 전파되어 사용자가 볼 수 있도록합니다
try { throw n; // throws an exception with a numeric value } catch (e) { if (e <= 50) { // statements to handle exceptions 1-50 } else { // cannot handle this exception, so rethrow throw e; } }
Specification | Status | Comment |
---|---|---|
{{SpecName('ES3')}} | {{Spec2('ES3')}} | Initial definition. Implemented in JavaScript 1.4 |
{{SpecName('ES5.1', '#sec-12.13', 'throw statement')}} | {{Spec2('ES5.1')}} | |
{{SpecName('ES6', '#sec-throw-statement', 'throw statement')}} | {{Spec2('ES6')}} | |
{{SpecName('ESDraft', '#sec-throw-statement', 'throw statement')}} | {{Spec2('ESDraft')}} |
{{Compat("javascript.statements.throw")}}