2015年7月23日 星期四

Java上課練習:例外處理


  • 設計一個學生例外類別,學生資料出問題時,產生此物件,提供相關的錯誤訊息
  • 設計 StudentException 繼承 RuntimeException


1
2
3
4
5
6
7
8
    //新增StudentException,繼承RuntimeException例外
    public class StudentException extends RuntimeException {
        //建構子
        public StudentException(String message) {
            super(message);//呼叫父類別建構子,設定錯誤訊息
        }

    }

  • 不允許建立學生物件時,名字少於兩個字
  • 發生名字字數太少問題時,建構子產生例外物件,將此例外拋出,讓對方程式知道出了什麼問題
  • 宣告方法可能拋出的例外,使用 throws
  • 方法中拋出例外,使用 throw


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
   //新增Student類別
public class Student {

    private String name;

    //建構子,宣告會拋出StudentException 例外
    public Student(String name) throws StudentException {
        if (name.length() < 2) {
            throw new StudentException("名字不能少於兩個字");
            //下方的程式不會執行
        }
        this.name = name;
    }

    @Override
    public String toString() {
        return "Student{" + "name=" + name + '}';
    }

}
新增StudentTest主類別


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
  import javax.swing.JOptionPane;

public class StudentTest {

    public static void main(String[] args) {
        String name = JOptionPane.showInputDialog("輸入name");
        Student st = new Student(name);
        System.out.println(st); // 自動呼叫 st.toString() 
    }

}
當輸入的名字少於2個字,則會顯示錯誤訊息


所以要加入例外處理


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
 import javax.swing.JOptionPane;

public class StudentTest {

    public static void main(String[] args) {
   boolean repeat;
        do {
            repeat = false;//重設 false
            try {
                String name = JOptionPane.showInputDialog("輸入name");
                Student st = new Student(name);
                System.out.println(st);
            } catch (StudentException se) { //取得例外錯誤訊息
                String msg = se.getMessage();
                JOptionPane.showMessageDialog(null, msg);
                repeat = true; //發生例外,需要重新輸入
            }
        } while (repeat);
    }

}

若不用例外處理,則程式要先判斷


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
 import javax.swing.JOptionPane;

public class StudentTest2 {

    public static void main(String[] args) {
        String name = null;
        do {
            name = JOptionPane.showInputDialog("輸入name");
        } while (name == null || name.length() < 2);
        Student st = new Student(name);
        System.out.println(st);
    }

}

沒有留言:

張貼留言