# 認識例外

程式在編譯時沒有錯誤訊息，卻在程式執行時發生錯誤。在 Java 中稱為「例外 exception」。

常見例外如：

* 整數除以0
* 輸入時型態的衝突 （例：希望使用者輸入數字，但卻輸入字母）
* 陣列索引值超出容許範圍
* .. 等）

除了使用冗長的 if else 或switch 敘述做判斷，Java 例外處理的機制不僅能提高效率、且增加程式穩定性。

試查看以下程式碼：

```
public class exception01 {

	public static void main(String[] args) {
		int arr[]=new int[5];
	      arr[10]=7;
	      System.out.println("例外範例1");
	}
}
```

以上範例程式是可以正常編譯的，但卻在執行時會顯示錯誤訊息：

![](/files/-MPaJvUNB0KCR8ennF6K)

> Exception in thread “main” java.lang.ArrayIndexOutOfBoundsException: 10
>
> at test.exception01.main(exception01.java:7)

從錯誤訊息當中，我們可以得知：第7行因為索引值超過容許範圍。\
Java 發現這個錯誤，並拋出例外；

其中，常串的英文錯誤可從字母大寫開頭做拆開整理：\
Array Index Out Of Bounds Exception : 10\
意指「 陣列 索引職 超出範圍例外：10 」。

經過以上簡單範例，得知 Java 預設的例外處理會 「拋出例外」 並且「停止程式執行」。

在 Java 當中，例外以類別的型態存在；而在 Java 那也含有預設的例外類別 來做處理（如以上範例）。\
不過 除了內建的例外處理之外，也允許自行定義例外類別的。

下篇將會帶入如何例外處理（exception handing）


---

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