本帖最後由 葉桔良 於 2022-9-23 21:06 編輯
除了捕捉Java拋出的例外物件,還可以利用關鍵字throw自行拋出例外物件。若在方法中拋出例外物件後,沒以try catch語法立即處理,則需在方法宣告列後方以throws關鍵字聲明該方法將會拋出例外物件,以強迫呼叫者處理例外。
- package test2;
- import java.util.Scanner;
- import java.util.InputMismatchException;
- public class Ch03 {
- public static void main(String[] args) throws MyException {
- int molecular,denominator;
- Scanner s = new Scanner(System.in);
- System.out.print("請輸入分子: ");
- molecular = s.nextInt();
- System.out.print("請輸入分母: ");
- denominator = s.nextInt();
- if(denominator==0)
- throw new MyException("分母不可為零");
- System.out.println(molecular+"/"+denominator+"="+(molecular/denominator));
- }
- }
- class MyException extends Exception{
- MyException(String str){
- super(str);
- }
- }
複製代碼 |