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
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
|
---
title: try...catch
slug: Web/JavaScript/Reference/Statements/try...catch
translation_of: Web/JavaScript/Reference/Statements/try...catch
---
<div>{{jsSidebar("Statements")}}</div>
<p>A <strong><code>try...catch</code> </strong>szerkezet utasítások futtatására, majd a keletkező kivételek érzékelésére, kezelésére való.</p>
<div>{{EmbedInteractiveExample("pages/js/statement-trycatch.html")}}</div>
<div>Megjegyzés: ebben a cikkben a kivétel szó az angol szaknyelvi exception, blokk pedig a block vagy clause szó fordítása.</div>
<p class="hidden">Az interaktív példa forrása egy GitHub gyűjteményben található. If you'd like to contribute to the interactive examples project, please clone <a href="https://github.com/mdn/interactive-examples">https://github.com/mdn/interactive-examples</a> and send us a pull request.</p>
<h2 id="Szerkezet">Szerkezet</h2>
<pre class="syntaxbox">try {
<em>try_statements</em>
}
[catch (<em>exception_var_1</em> if <em>condition_1</em>) { // nem szabványos
<em>catch_statements_1</em>
}]
...
[catch (<em>exception_var_2</em>) {
<em>catch_statements_2</em>
}]
[finally {
<em>finally_statements</em>
}]</pre>
<dl>
<dt><code>try_statements</code></dt>
<dd>Azok az utasítások, amelyek kivételt válthatnak ki.</dd>
</dl>
<dl>
<dt><code>catch_statements_1</code>, <code>catch_statements_2</code></dt>
<dd>Azok az utasítások, amelyek akkor hajtódnak végre, ha valami kivételt vált ki a <code>try</code> blokkban.</dd>
</dl>
<dl>
<dt><code>exception_var_1</code>, <code>exception_var_2</code></dt>
<dd>Annak a változónak a neve, amelyben az utána következő <code>catch</code> blokkban elérhető lesz a kivételobjektum (<code>Exception</code>).</dd>
</dl>
<dl>
<dt><code>condition_1</code></dt>
<dd>Valamilyen feltétel (mint egy if() kifejezésben).</dd>
</dl>
<dl>
<dt><code>finally_statements</code></dt>
<dd>Azok az utasítások, amelyeket a <code>try</code> blokk után le kell futtatni, tehát ezek attól függetlenül végrehajtódnak, hogy a <code>try</code> blokkban történt-e kivétel.</dd>
</dl>
<h2 id="Kifejtés">Kifejtés</h2>
<p>A <code>try</code> szerkezetnek 3 megjelenési formája van:</p>
<ol>
<li><code>try...catch</code></li>
<li><code>try...finally</code></li>
<li><code>try...catch...finally</code></li>
</ol>
<p>A <code>try</code>, a <code>catch</code> és a <code>finally</code> blokk egy vagy több utasításból állhat. A kapcsos zárójelek használata kötelező, még akkor is, ha egy utasításból áll csak a blokk. A <code>try</code> blokk után legalább egy <code>catch</code> vagy <code>finally</code> blokknak kell lennie.:</p>
<p>A <code>catch</code> blokk tartalmazza azokat az utasításokat, amelyek akkor hajtódnak végre, ha valami kivételt vált ki a <code>try</code> blokkban. Ha valami kivételt vált ki, a try blokk végrehajtása azonnal megszakad, és a catch blokk hajtódik végre. Ha nem történik kivétel, a catch blokk nem hajtódik végre.</p>
<p>A finally blokk végrehajtása a try és a catch blokk(ok) végrehajtása után, közvetlenül a blokk utáni utasítások előtt. Mindig végrehajtódik, attól függetlenül, hogy a try blokk sikeres volt-e.</p>
<p>A try szerkezetek egymásba ágyazhatóak. Ha egy beágyazott try blokkhoz nem tartozik catch blokk, az azt tartalmazó try blokkhoz tartozó catch/finally fog végrehajtódni.</p>
<p>A try szerkezettel a JavaScript kivételeit is lehet kezelni. További információ róluk: <a href="/en-US/docs/Web/JavaScript/Guide" title="en/JavaScript/Guide">JavaScript Guide</a>.</p>
<h3 id="Feltétel_nélküli_catch_blokk">Feltétel nélküli catch blokk</h3>
<p>Egyszerű, feltétel nélküli catch blokk esetén bármilyen kivétel váltódik ki, ugyanaz a blokk fog végrehajtódni. Például</p>
<pre class="brush: js">try {
throw 'myException'; // generates an exception
}
catch (e) {
// statements to handle any exceptions
logMyErrors(e); // pass exception object to error handler
}
</pre>
<p>A catch blokk használata során meg kell adnunk egy változónevet, ez a változó fogja tárolni a kivételobjektumot. A catch blokkban megadott változó élettartama eltér a szokásostól: a változó a catch blokk végrehajtása előtt jön létre, és a végrehajtás után nem elérhető.</p>
<h3 id="Feltételes_catch_blokk">Feltételes catch blokk</h3>
<p>You can also use one or more conditional <code>catch</code> clauses to handle specific exceptions. In this case, the appropriate <code>catch</code> clause is entered when the specified exception is thrown. In the following example, code in the <code>try</code> block can potentially throw three exceptions: {{jsxref("TypeError")}}, {{jsxref("RangeError")}}, and {{jsxref("EvalError")}}. When an exception occurs, control transfers to the appropriate <code>catch</code> clause. If the exception is not one of the specified exceptions and an unconditional <code>catch</code> clause is found, control transfers to that <code>catch</code> clause.</p>
<p>If you use an unconditional <code>catch</code> clause with one or more conditional <code>catch</code> clauses, the unconditional <code>catch</code> clause must be specified last. Otherwise, the unconditional <code>catch</code> clause will intercept all types of exception before they can reach the conditional ones.</p>
<p>Emlékeztető: ez a lehetőség nem az ECMAScript szabvány része.</p>
<pre class="brush: js">try {
myroutine(); // may throw three types of exceptions
} catch (e if e instanceof TypeError) {
// statements to handle TypeError exceptions
} catch (e if e instanceof RangeError) {
// statements to handle RangeError exceptions
} catch (e if e instanceof EvalError) {
// statements to handle EvalError exceptions
} catch (e) {
// statements to handle any unspecified exceptions
logMyErrors(e); // pass exception object to error handler
}
</pre>
<p>Here is the same "Conditional catch clauses" using code that conforms to ECMAScript specification (obviously it's more verbose, but works everywhere):</p>
<pre class="brush: js">try {
myroutine(); // may throw three types of exceptions
} catch (e) {
if (e instanceof TypeError) {
// statements to handle TypeError exceptions
} else if (e instanceof RangeError) {
// statements to handle RangeError exceptions
} else if (e instanceof EvalError) {
// statements to handle EvalError exceptions
} else {
// statements to handle any unspecified exceptions
logMyErrors(e); // pass exception object to error handler
}
}
</pre>
<h3 id="The_exception_identifier">The exception identifier</h3>
<p>When an exception is thrown in the <code>try</code> block, <em><code>exception_var</code></em> (e.g. the <code>e</code> in <code>catch (e)</code>) holds the value specified by the <code>throw</code> statement. You can use this identifier to get information about the exception that was thrown. As of Firefox 58, when the exception is unused, the identifier can be omitted, as in</p>
<pre class="brush: js">function isValidJSON(text) {
try {
JSON.parse(text);
return true;
} catch {
return false;
}
}
</pre>
<p>This identifier is local to the <code>catch</code> clause. That is, it is created when the <code>catch</code> clause is entered, and after the <code>catch</code> clause finishes executing, the identifier is no longer available.</p>
<h3 id="A_finally_blokk">A <code>finally</code> blokk</h3>
<p>A finally blokk azokat az utasításokat tartalmazza, amelyeket a catch blokk(ok) után, de a try-catch-finally szerkezet előtt kell végrehajtani. Mindenképpen végrehajtódik, attól függetlenül, hogy a try blokkban váltódott-e ki kivétel. A finally blokk megléte elfogadhatóvá teszi a catch blokk hiányát, de a kivételek megjelennek a blokkon kívül is. Amennyiben hiányzik a catch blokk, először a try-ban kiváltódott kivételek jelennek meg, majd ezután hajtódik végre a finally blokk.</p>
<p>A finally blokkot gyakran használják a program hiba esetén történő leállása előtti feladatok elvégzésére.</p>
<p>Enyhén szólva furcsának tűnhet, hogy a JavaScript kivételekhez kapcsolódó részében szerepel egy olyan ág is, ami attól függetlenül végrehajtódik, hogy váltódott-e ki kivétel. Ennek azomban, a látszattal ellentétben van értelme. A hangsúly nem azon van, hogy a finally blokk mindig végrehajtódik, hanem hogy az azt követő utasítások nem feltétlenül.</p>
<p>Például ha egy másik kivétel váltódik ki egy try-catch blokkon belül, semmilyen más kód ugyanabban a külső try-catch blokkban nem fog végrehajtódni.</p>
<p>For instance, if another exception occurs inside a try's catch-block, any remaining code in the same outer try-block enclosing that try..catch (or in the main flow, if not in an outer try-block) , will not get executed, since control is immediately transferred to the outer try's catch-block (or the internal error-generator, if not in a try-block). </p>
<p>Thus, any routine cleanup code done in that enclosed (or the main) section before it exits, will be skipped. However, If the try-block has a finally-block, then that finally-block code will be executed first to permit any such cleanup, and THEN the other try's catch-block (or the error-generator) will get control to handle the second exception. </p>
<p>Now, if that routine cleanup must be done whether or not the try..catch code succeeds, then if the finally-block only executed after an exception, the same cleanup code would have to be duplicated both inside and outside the finally-block, and therefore there is no reason not to have just the finally-block alone, and let it execute regardless of exceptions or not.</p>
<p>The following example opens a file and then executes statements that use the file (server-side JavaScript allows you to access files). If an exception is thrown while the file is open, the <code>finally</code> clause closes the file before the script fails. The code in <code>finally</code> also executes upon explicitly returning from <code>try</code> or <code>catch</code> block.</p>
<pre class="brush: js">openMyFile();
try {
// tie up a resource
writeMyFile(theData);
}
finally {
closeMyFile(); // always close the resource
}
</pre>
<h2 id="Példák">Példák</h2>
<h3 id="Beágyazott_try_blokkok">Beágyazott try blokkok</h3>
<p>Először is, nézzük meg ezt:</p>
<pre class="brush: js">try {
try {
throw new Error('hoppácska');
}
finally {
console.log('finally blokk');
}
}
catch (ex) {
console.error('külső catch blokk', ex.message);
}
// Kimenet:
// "finally blokk"
// "külső catch blokk" "hoppácska"
</pre>
<p>Now, if we already caught the exception in the inner try-block by adding a catch block</p>
<pre class="brush: js">try {
try {
throw new Error('hoppácska');
}
catch (ex) {
console.error('belső catch blokk', ex.message);
}
finally {
console.log('finally blokk');
}
}
catch (ex) {
console.error('outer', ex.message);
}
// Kimenet:
// "belső catch blokk" "hoppácska"
// "finally blokk"
</pre>
<p>Most pedig dobjuk tovább a kivételt:</p>
<pre class="brush: js">try {
try {
throw new Error('hoppácska');
}
catch (ex) {
console.error('belső catck blokk', ex.message);
throw ex;
}
finally {
console.log('finally blokk');
}
}
catch (ex) {
console.error('külső catck blokk', ex.message);
}
// Output:
// "belső catck blokk" "hoppácska"
// "finally blokk"
// "külső catck blokk" "hoppácska"
</pre>
<p>Minden kivételt csak a legközelebbi catch blokk fog elkapni, kivéve ha innen tovább dobjuk. Ez esetben a belső catch blokkból dobott kivételt a külső try-hez tartozó catch blokk fogja elkapni.</p>
<h3 id="return_használata_a_finally_blokkban"><code>return</code> használata a finally blokkban</h3>
<p>Ha a finally blokk értéket ad vissza, ez az érték a teljes try-catch-finally szerkezet vissszatérési értékévé válik, a try és catch blokkokban lévő return utasításoktól függetlenül. Ebbe beletartoznak a catch blokkon belül dobott kivételek is.</p>
<pre class="brush: js">(function() {
try {
try {
throw new Error('hoppácska');
}
catch (ex) {
console.error('belső catch blokk', ex.message);
throw ex;
}
finally {
console.log('finally blokk');
return;
}
}
catch (ex) {
console.error('külső', ex.message);
}
})();
// Kimenet:
// "belső catch blokk" "hoppácska"
// "finally blokk"</pre>
<p>The outer "oops" is not thrown because of the return in the finally block. The same would apply to any value returned from the catch block.</p>
<h2 id="Specifikációk">Specifikációk</h2>
<table class="standard-table">
<tbody>
<tr>
<th scope="col">Specifikáció</th>
<th scope="col">Státusz</th>
<th scope="col">Megjegyzés</th>
</tr>
<tr>
<td>{{SpecName('ES3')}}</td>
<td>{{Spec2('ES3')}}</td>
<td>
<p>Az első leírás. A JavaScript 1.4-ben lett megvalósítva.</p>
</td>
</tr>
<tr>
<td>{{SpecName('ES5.1', '#sec-12.14', 'try statement')}}</td>
<td>{{Spec2('ES5.1')}}</td>
<td></td>
</tr>
<tr>
<td>{{SpecName('ES6', '#sec-try-statement', 'try statement')}}</td>
<td>{{Spec2('ES6')}}</td>
<td></td>
</tr>
<tr>
<td>{{SpecName('ESDraft', '#sec-try-statement', 'try statement')}}</td>
<td>{{Spec2('ESDraft')}}</td>
<td>Nem része a jelenleg ECMA-262 szabványnak: Több catch blokk és feltételes bokkok (SpiderMonkey kiterjesztés, JavaScript 1.5).</td>
</tr>
</tbody>
</table>
<h2 id="Browser_compatibility">Browser compatibility</h2>
<p>{{Compat("javascript.statements.try_catch")}}</p>
<h2 id="See_also">See also</h2>
<ul>
<li>{{jsxref("Error")}}</li>
<li>{{jsxref("Statements/throw", "throw")}}</li>
</ul>
|