# 於程式中拋出例外

在例外的章節中，使用了 try-catch-finally，本篇解說拋出例外並由 catch接收例外。

> 拋出例外會使用到 throw 這個關鍵字。
>
> ```
> throw 例外類別產生之物件
> ```

而拋出例外時， throw 敘述應使用 new 關鍵字產生物件。

以下範例：令 a,b兩變數，其中b為0 來測試以上的說法。

```
int a=100,b=0;

try
{
  if(b==0)
  throw new ArithmeticException();
  else
  System.out.println(a+"/"+b+"="+a/b);
}
catch(ArithmeticException e)
{
  System.out.println(e+" 被拋出");
}
```

如果當b等於0，就拋出 ArithmeticException 這個例外；\
如果b 不等於0，那麼就計算 a/b。

在 [認識例外](/java-14/java-14-1.md) 中提過一個常見例外：整數除以0

因此此範例執行後，會印出

```
java.lang.ArithmeticException 被拋出
```

可能會有疑問，即使沒有撰寫 throw new ArithmeticException(); 程式也會拋出內建的例外。

本篇的用意在於，若有自己寫的例外類別 程式是無法自動拋出的，\
因此必須透過本篇的介紹 來拋出。


---

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