# 例外處理

在上一篇中的範例，因為在程式第7行就已把例外拋出，因此從第8行開始就不被執行了。

![](/files/-MPaJvUNB0KCR8ennF6K)

但如果能夠捕捉(catch) 例外的程式碼，就能妥善的處理；這樣的方式稱為例外處理（exception handing）。

## 例外處理基本格式

```
try
{
    想要檢查的敘述;
}
catch()
{
    當例外發生，處理的敘述;
}
finally
{
    一定被執行的敘述;
}
```

將上述語法的步驟繪成以下流程圖，進一步了解運作方式：

![](/files/-MPaKEtDV_u3UTHH3r7N)

1. 若 try 區塊有例外發生，程式會中斷並拋出例外類別產生的物件。
2. 若拋出的物件是 catch 想要捕捉的例外，將會執行catch中的敘述。
3. 無論 try 有例外發生，或是catch 有無捕捉到例外，皆會執行 finally 中的敘述。
4. 最後就會執行 try catch finally 以外的程式敘述。

> 注意：格式中的大括號 {} ，即使敘述只有一行也不能省略！

下篇將會開始帶入如何例外處理（exception handing）的實作範例。<br>


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://java.4-x.tw/java-14/java-14-2.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
