1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
|
---
title: throw
slug: Web/JavaScript/Referencje/Polecenia/throw
tags:
- Dokumentacja_JavaScript
- Dokumentacje
- JavaScript
- Strony_wymagające_dopracowania
- Wszystkie_kategorie
translation_of: Web/JavaScript/Reference/Statements/throw
---
<div>{{jsSidebar("Statements")}}</div>
<p>The <strong><code>throw</code> statement</strong> throws a user-defined exception. Execution of the current function will stop (the statements after <code>throw</code> won't be executed), and control will be passed to the first <a href="/en-US/docs/Web/JavaScript/Reference/Statements/try...catch"><code>catch</code></a> block in the call stack. If no <code>catch</code> block exists among caller functions, the program will terminate.</p>
<div>{{EmbedInteractiveExample("pages/js/statement-throw.html")}}</div>
<h2 id="Syntax">Syntax</h2>
<pre class="syntaxbox">throw <em>expression</em>; </pre>
<dl>
<dt><code>expression</code></dt>
<dd>The expression to throw.</dd>
</dl>
<h2 id="Description">Description</h2>
<p>Use the <code>throw</code> statement to throw an exception. When you throw an exception, <code>expression</code> specifies the value of the exception. Each of the following throws an exception:</p>
<pre class="brush: js">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</pre>
<p>Also note that the <code>throw</code> statement is affected by <a href="/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#Automatic_semicolon_insertion">automatic semicolon insertion (ASI)</a> as no line terminator between the <code>throw</code> keyword and the expression is allowed.</p>
<h2 id="Examples">Examples</h2>
<h3 id="Throw_an_object">Throw an object</h3>
<p>You can specify an object when you throw an exception. You can then reference the object's properties in the <code>catch</code> block. The following example creates an object of type <code>UserException</code> and uses it in a <code>throw</code> statement.</p>
<pre class="brush: js">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
}
</pre>
<h3 id="Another_example_of_throwing_an_object">Another example of throwing an object</h3>
<p>The following example tests an input string for a U.S. zip code. If the zip code uses an invalid format, the throw statement throws an exception by creating an object of type <code>ZipCodeFormatException</code>.</p>
<pre class="brush: js">/*
* 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
</pre>
<h3 id="Rethrow_an_exception">Rethrow an exception</h3>
<p>You can use <code>throw</code> to rethrow an exception after you catch it. The following example catches an exception with a numeric value and rethrows it if the value is over 50. The rethrown exception propagates up to the enclosing function or to the top level so that the user sees it.</p>
<pre class="brush: js">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;
}
}
</pre>
<h2 id="Specifications">Specifications</h2>
<table class="standard-table">
<tbody>
<tr>
<th scope="col">Specification</th>
<th scope="col">Status</th>
<th scope="col">Comment</th>
</tr>
<tr>
<td>{{SpecName('ES3')}}</td>
<td>{{Spec2('ES3')}}</td>
<td>Initial definition. Implemented in JavaScript 1.4</td>
</tr>
<tr>
<td>{{SpecName('ES5.1', '#sec-12.13', 'throw statement')}}</td>
<td>{{Spec2('ES5.1')}}</td>
<td> </td>
</tr>
<tr>
<td>{{SpecName('ES6', '#sec-throw-statement', 'throw statement')}}</td>
<td>{{Spec2('ES6')}}</td>
<td> </td>
</tr>
<tr>
<td>{{SpecName('ESDraft', '#sec-throw-statement', 'throw statement')}}</td>
<td>{{Spec2('ESDraft')}}</td>
<td> </td>
</tr>
</tbody>
</table>
<h2 id="Browser_compatibility">Browser compatibility</h2>
<p>{{Compat("javascript.statements.throw")}}</p>
<h2 id="See_also">See also</h2>
<ul>
<li><a href="/en-US/docs/Web/JavaScript/Reference/Statements/try...catch"><code>try...catch</code></a></li>
</ul>
|