我寫的事例,歡迎討論
package com.exception;
import java.util.*;
public class Test {
?? ?String[] book = {"高數(shù)","英語","語文","數(shù)據(jù)","java"};
?? ?public static void main(String[] args) {
?? ??? ?// TODO Auto-generated method stub
?? ??? ?Scanner scanner = new Scanner(System.in);
?? ??? ?System.out.println("輸入命令:1-按照名稱查找圖書;2-按照序號查找圖書");
?? ??? ?int receive = scanner.nextInt();
?? ??? ?Test test = new Test();
?? ??? ?try {
?? ??? ??? ?switch(receive) {
?? ??? ??? ??? ?case 1:
?? ??? ??? ??? ??? ?test.book();
?? ??? ??? ??? ??? ?break;
?? ??? ??? ??? ?case 2:
?? ??? ??? ??? ??? ?test.num();
?? ??? ??? ??? ??? ?break;
?? ??? ??? ??? ?default:
?? ??? ??? ??? ??? ?throw new NoBookException("命令輸入錯誤!請根據(jù)提示輸入數(shù)子命令!");
?? ??? ??? ?}
?? ??? ?}catch(NoBookException e) {
?? ??? ??? ?e.printStackTrace();
?? ??? ??? ?System.out.println("輸入命令:1-按照名稱查找圖書;2-按照序號查找圖書");
?? ??? ?}
?? ?}
?? ?
?? ?public void book() throws NoBookException{
?? ??? ?System.out.println("輸入圖書名稱:");
?? ??? ?Scanner sb = new Scanner(System.in);
?? ??? ?String name = sb.next();
?? ??? ?boolean flag = false;
?? ??? ?for(String bk:book) {
?? ??? ??? ?if(name.equals(bk)) {
?? ??? ??? ??? ?flag = true;
?? ??? ??? ??? ?break;
?? ??? ??? ?}
?? ??? ?}
?? ??? ?if(flag) {
?? ??? ??? ?System.out.println("book:"+name);
?? ??? ?}else {
?? ??? ??? ?throw new NoBookException("圖書不存在!");
?? ??? ?}
?? ?}
?? ?
?? ?public void num() throws NoBookException{
?? ??? ?System.out.println("輸入圖書序號:");
?? ??? ?Scanner sn = new Scanner(System.in);
?? ??? ?int i = sn.nextInt();
?? ??? ?String str = book[i-1];
?? ??? ?if(str == null || str.equals("")) {
?? ??? ??? ?throw new NoBookException("圖書不存在!");
?? ??? ?}else {
?? ??? ??? ?System.out.println("book:"+str);
?? ??? ?}
?? ?}
}
2018-12-05
沒有異常提示語句啊
2018-11-15
為什么,你在try{}用到book()方法,而這個方法后面才定義,在main方法中,是從上到下執(zhí)行的,雖然你有用try鋪抓異常,但最好還是先定義后使用;
2018-11-15
NoBookException??這個是你自己定義的異常嗎?