# 於指定函數拋出例外

在上篇 [於程式中拋出例外](/java-14/java-14-6.md)  介紹了如何在程式中拋出例外，\
那麼若遇到函數中的程式碼發生例外，卻沒有 try-catch-finally 區塊來進行捕捉例外；\
因此，

> 如果函數會拋出例外，那麼可以將函數的 呼叫 撰寫在 try-catch-finally 區塊。
>
> ```
> 函數名稱() throws 例外類別
> {
>    函數中之程式碼
> }
> ```

與上篇不同在於 throw 是否有加 s，兩者關鍵字是有不同的。

* 函數內部拋出例外，使用 throw
* 指定函數拋出例外，使用 throws

讓我們將上篇範例修改一下：

將 a/b 寫成一個函數

```
public static void abc(int a,int b) throws ArithmeticException
{
   int ans;
   ans=a/b;
   System.out.println(a+"/"+b+"="+ans);
}
```

因此在 try-catch-finally 區塊就可以直接呼叫

```
try
{
   abc(100,0);
}
catch(ArithmeticException e)
{
   System.out.println(e+" 被拋出");
}
```

當呼叫abc(100,0) 時，b為0 因此會拋出 ArithmeticException 例外。\
而本範例是撰寫在同個 class 內，因此可以直接呼叫abc() 函數

```
public static void abc(int a,int b) throws ArithmeticException
{
   int ans;
   ans=a/b;
   System.out.println(a+"/"+b+"="+ans);
}

public static void main(String args[])
{
   try
   {
      abc(100,0);
   }
   catch(ArithmeticException e)
   {
      System.out.println(e+" 被拋出");
   }
}
```

若在不同類別，想要拋出例外；\
我們只要稍微改一下：

函數是在 test 類別中，在main() 中撰寫try-catch-finally 區塊來處理例外；\
這時只需要在呼叫函數時，加上函數所在的類別名稱即可。

以下範例：

```
class test
{
    public static void abc(int a,int b) throws ArithmeticException
    {
       int c=a/b;
       System.out.println(a+"/"+b+"="+c);
    }
}

public class throws_ex
{
   public static void main(String args[])
   {
      try
      {
         test.abc(100,0);
      }
      catch(ArithmeticException e)
      {
         System.out.println(e+" throwed");
      }
   }
}
```


---

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