異常捕獲提問
package com.imooc;
import java.util.Scanner;
public class test1 {
private static Scanner console=new Scanner(System.in);
public static void main(String[] args) {
// TODO Auto-generated method stub
String[] books = { "C語言", "數(shù)據(jù)結(jié)構(gòu)", "匯編語言", "高數(shù)", "大學(xué)語文", "毛概" }; ??
? ? while(true){
? ? System.out.println("輸入命令:1-按照名稱查找圖書;2-按照序號查找圖書");
? ? String book;
? ? try{
? ? int command=inputCommand();
? ? switch(command){
? ? case 1:
? ? book=getBookByName(books);
? ? System.out.println("book"+book);
? ? break;
? ? case 2:
? ? book=getBookByNumber(books);
? ? System.out.println("book"+book);
? ? break;
? ? case -1:
? ? ? ?System.out.println("命令輸入錯誤!請根據(jù)提示輸入數(shù)字命令!");
? ? ? ?continue;
? ? default:
? ? System.out.println("命令輸入錯誤!");
? ? continue;
? ? }
? ? break;
? ? }catch(Exception bne){
? ? System.out.println(bne.getMessage());
? ? }
? ? }
? ?
}
? ? private static String getBookByName(String[] books) throws Exception{
? ? ? ?System.out.println("輸入圖書名稱:");
? String name=console.next();
? ?for(int i=0;i<books.length;i++){
? ? if(name.equals(books[i]))
? ? return books[i];
? ?} ??
throw new Exception("圖書不存在!");
}
private static String getBookByNumber(String[] books) throws Exception{
while(true){
System.out.println("輸入圖書序號:");
try{
int index=inputCommand();
if(index==-1){
System.out.println("命令輸入錯誤!請根據(jù)提示輸入數(shù)字命令!");
continue;
}
String book=books[index];
return book;
}catch(ArrayIndexOutOfBoundsException e){
Exception bookNotExists=new Exception("圖書不存在!");
bookNotExists.initCause(e);
throw bookNotExists;
}
}
}
? ? private static int inputCommand(){
int command;
try{
command=console.nextInt();
return command;
}catch(Exception e){
console=new Scanner(System.in);
return -1;
}
?
?}
}
請問為什么這里面都會用到try ? catch ,只有我加的下劃線方法沒有try catch?
2016-08-09
因?yàn)樗某绦驔]有要拋出異常的地方,他就是個循環(huán)遍歷,而且他的return返回值方便給下面異常中調(diào)用
2016-08-09
try catch是檢測異常并處理 你下劃線那里 遍歷book[]之后依舊沒有return 在代碼的運(yùn)行上并沒有異常 所以try catch并不會捕獲到信息(邏輯上的異常 但是沒有異常類 就是我們自己知道異常了 但是機(jī)器并不會檢測出異常 所以 人為的拋出了一個異常)
2016-08-09
try catch是檢測異常并處理 你下劃線那里 遍歷book[]之后依舊沒有return 在代碼的運(yùn)行上并沒有異常 所以try catch并不會捕獲到信息(邏輯上的異常 但是沒有異常類 就是我們自己知道異常了 但是機(jī)器并不會檢測出異常 所以 人為的拋出了一個異常)