package org.java.exception; /** * 图书不存在异常 * @author 1 * */ public class BookNotNullException extends Exception{ public BookNotNullException() { } public BookNotNullException(String message) { super(message); } } package org.java.exception; /** * 指令输入错误异常; * @author 1 * */ public class InstructNotException extends Exception{ public InstructNotException() { } public InstructNotException(String message) { super(message); } }
package org.java.exception; import java.util.Scanner; public class BookTest { public static void main(String[] args){ String[] str = {"语文","高数","英文","java","c","c++","jsp","PHP","Jquery","生物"}; Scanner input = new Scanner(System.in); int state=1; System.out.println("欢迎进入图书查询系统>>>>>>>"); do{ System.out.println("请选择查询条件 1按索引查询 2按书名查询"); try { int a = input.nextInt(); if(a==1){//输入为1时 System.out.println("输入1-10进行查询"); int b = input.nextInt(); try { if(b>0&&b<=10) { System.out.println("book:"+str[b-1]); }else { throw new BookNotNullException(); } } catch (BookNotNullException e) { System.out.println("图书不存在异常"); }finally { System.out.println("是否继续查询:1是 2否"); int d = input.nextInt(); if(d==1) { state = 1; }else { state =0; } } }else if(a==2){//书名查询时 不存在 System.out.println("请输入查询的书名"); String book = input.next(); try { int c = findBookByName(book,str); if(c==0) { throw new BookNotNullException(); //抛出异常 } } catch (BookNotNullException e) { System.out.println("图书不存在异常"); }finally { System.out.println("是否继续查询:1是 2否"); int d = input.nextInt(); if(d==1) { state = 1; }else { state =0; } } }else { throw new InstructNotException();//指令输入错误异常 } } catch (InstructNotException e ) { System.out.println("指令输入错误异常"); System.out.println("是否继续查询:1是 2否"); int d = input.nextInt(); if(d==1) { state = 1; }else { state =0; } } }while(state!=0); System.out.println("结束查询"); } public static int findBookByName(String book,String[] str) { for(int i=0;i<str.length;i++) { if(book.equals(str[i])) { System.out.println("book:"+str[i]); return 1; } } return 0; } }
throw
new
BookNotNullException();
请问抛这个异常的时候,不需要在方法头进行声明吗?
试一下把查询条件写成函数
public void menu (){ System.out.println("请选择查询条件 1按索引查询 2按书名查询"); } 输入错误的时候 调用menu()返回选择界面