代码不长,感觉自己对于异常理解的还不够深刻,throw出去异常最后解决不了为什么要throw。。而且我把throw exc用return null代替竟然也不会报错。。这个有谁可以解释下不。。
test类
package books;
import java.util.Scanner;
public class test {
static Scanner input = new Scanner(System.in);
public static void main(String[] args) {
// TODO Auto-generated method stub
test t = new test();
System.out.println("输入命令:\n1-按照名称查找图书;2-按照序号查找图书");
try{
switch(input.next()){
case "1":
System.out.println("输入图书名称");
String receive1 = t.getBooksByName();
System.out.println(receive1);
break;
case "2":
System.out.println("输入图书序号");
String receive2 = t.getBooksByNum();
System.out.println(receive2);
break;
default:
System.out.println("请正确输入!!");
}
}catch(Exception e){
System.out.println("执行时出现了异常");/*但是这么编写不会有异常,
如果有小伙伴想看看catch执行的效果可以将后面getBooksByNum()中的next()改为
nextInt(),这样在先输入2后,
在输入sdafadsf这样的字符型就可以产生异常*/
System.out.println(e.getMessage());//没有机会显示这行
}
}
public static String getBooksByNum() throws Exception{
try{
switch(input.next()){
case "1":
return "book:语文";
case "2":
return "book:数学";
case "3":
return "book:英语";
case "4":
return "book:java";
default:
return "没有所需书籍!";
}
}catch(Exception e){
Exception exc = new Exception("输入了非整型导致异常");
exc.initCause(e);
throw exc;
}
}
public static String getBooksByName() throws Exception{
try{String name = input.next();
switch(name){
case "语文":
return "book:语文";
case "数学":
return "book:数学";
case "英语":
return "book:英语";
case "java":
return "book:java";
default:
return"没有名字是"+name+"的书籍!";
}
}catch(Exception e){
Exception exc = new Exception("输入了非字符型导致异常");
exc.initCause(e);
throw exc;
}
}
}