# 例外類別捕捉多個例外

於 [認識例外類別](/java-14/java-14-4.md) 文末提到了，catch() 括號內只接收一種類別，\
那麼如何捕捉多個例外？

本篇將會介紹：

* 捕捉一種以上的例外
* 捕捉所有例外

在 [例外處理](/java-14/java-14-2.md) 了解例外處理的基本格式：

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

想要捕捉一種以上的例外很簡單！我們只需要：

```
try
{
    想要檢查的敘述;
}
catch(第一種例外類別 e)
{
    當例外發生，處理的敘述;
}
catch(第二種例外類別 e)
{
    當例外發生，處理的敘述;
}

finally
{
    一定被執行的敘述;
}
```

透過多個 catch() 就可以捕捉一種一上的例外囉！ （該不會遭毆 σ(´∀｀\*)

那麼如何捕捉所有例外！？

在 [認識例外類別](/java-14/java-14-4.md) 提過的流程圖：

![](/files/-MPaKml_nWpGgZ5bc9N3)

我們只需要在類別部分，直接加上最上頭的 Excepiton 就可以捕捉所有的例外了！

```
catch(Exception e)
{
    當例外發生，處理的敘述;
}
```

當然要注意，提到的 RuntiomeException 類別，與 IOException類別；\
所以如果使用 Excepiton 的話，是必須撰寫例外處理的程式敘述。

最後還是有一點是需要更多加注意的：\
當我們捕捉多個例外時，範圍小的例外要先撰寫，而範圍大的例外排在之後。

如上方提到 Excepiton，因為是範圍較大的例外，因此必須排在範圍較小的後面，參考底下：

```
catch(ArrayIndexOutOfBoundsException e)
{
 當例外發生，處理的敘述;
}

catch(Exception e)
{
 當例外發生，處理的敘述;
}
```

流程圖中，ArrayIndexOutOfBoundsException 是範圍較小的例外，\
因此優先撰寫，而 Excepiton 排在範圍較小的後面。

> 如果把範圍大的先寫在前，那麼不管何種例外都會被捕捉，\
> 會有這樣的寫法，我的想法是 先透過範圍小的例外做過濾；如果有未過濾到的部分就可透過大範圍的例外來捕捉。


---

# 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-5.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.
