---
description: 🚧 under construction
---

# try-catch-finally

* [JS](../..) ⟩ [statement](../../grammar/statement) ⟩ [control flow](../../grammar/statement/flow) ⟩ [jump](../../grammar/statement/flow/jump) ⟩ try-catch-finally
* [JS](../..) ⟩ [error](../../err) ⟩ [handling]() ⟩ try-catch-finally&#x20;

{% hint style="success" %}
([statement](../../grammar/statement "mention"))&#x20;

```javascript
try { ... }            // run code that may throw.
catch (err) { ... }    // error handling (and∨ rethrow)
finally { ... }        // cleanup code
```
{% endhint %}

{% tabs %}
{% tab title="🧨 雷區" %}
{% hint style="danger" %}
一但使用 <mark style="color:blue;">`try`</mark>，一定要用 <mark style="color:blue;">`catch(err)`</mark> 去抓「<mark style="color:yellow;">**所有的錯誤**</mark>」，否則可能會<mark style="color:red;">**漏掉**</mark>「<mark style="color:yellow;">自己沒有預期的錯誤</mark>」:exclamation:

```javascript
try {
  noSuchFunc();  // ⛔ ReferenceError (not catched)
} catch(err) { 
  // `console.log(err)` omitted ... (dangerous)❗
  // or, `throw err` omitted ...
}
// the code will continue executing happily❗
```
{% endhint %}
{% endtab %}

{% tab title="⭐️ 重點" %}
{% hint style="warning" %}
if a <mark style="color:purple;">**finally clause**</mark> <mark style="color:yellow;">**issues**</mark> a [return](../../grammar/statement/flow/jump/return "mention") <mark style="color:yellow;">**statement**</mark>, the method <mark style="color:yellow;">**returns**</mark>**&#x20;**<mark style="color:green;">**normally**</mark>, even if an exception has been thrown and has not yet been handled.
{% endhint %}

{% hint style="info" %}
<mark style="color:yellow;">**bare**</mark>**&#x20;**<mark style="color:purple;">**catch clause**</mark>

in <mark style="color:yellow;">**ES2019**</mark> and later, the [**parentheses**](../../grammar/token/punctuator/parentheses) / (<mark style="color:blue;">`error`</mark>) [**identifier**](../../grammar/token/id) in the catch clause <mark style="color:green;">**can**</mark>**&#x20;**<mark style="color:yellow;">**be omitted**</mark>.
{% endhint %}
{% endtab %}

{% tab title="👥 相關" %}
* [](<> "mention")
* [throw](throw "mention")
{% endtab %}

{% tab title="📗 參考" %}
* [ ] [javascript-the-definitive-guide](../../../master/ref/javascript-the-definitive-guide "mention") ⟩ 5.5.7 try/catch/finally
{% endtab %}

{% tab title="📘 手冊" %}
* [try...catch](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/try...catch)
{% endtab %}
{% endtabs %}
