Comment on page
於指定函數拋出例外
如果函數會拋出例外,那麼可以將函數的 呼叫 撰寫在 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");
}
}
}
Last modified 2yr ago