# 於程式中拋出例外

在例外的章節中，使用了 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。

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

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

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

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

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