异常捕获提问

来源:1-7 Java 中的异常链

菜鸟的羽毛

2016-08-09 15:38

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语言", "数据结构", "汇编语言", "高数", "大学语文", "毛概" };   

    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("命令输入错误!请根据提示输入数字命令!");

       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("命令输入错误!请根据提示输入数字命令!");

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?

写回答 关注

3回答

  • 幕布斯2744493
    2016-08-09 15:58:19

    因为他的程序没有要抛出异常的地方,他就是个循环遍历,而且他的return返回值方便给下面异常中调用

  • Joyed
    2016-08-09 15:52:42

    try catch是检测异常并处理 你下划线那里 遍历book[]之后依旧没有return 在代码的运行上并没有异常 所以try catch并不会捕获到信息(逻辑上的异常 但是没有异常类 就是我们自己知道异常了 但是机器并不会检测出异常 所以 人为的抛出了一个异常)

  • Joyed
    2016-08-09 15:52:27

    try catch是检测异常并处理 你下划线那里 遍历book[]之后依旧没有return 在代码的运行上并没有异常 所以try catch并不会捕获到信息(逻辑上的异常 但是没有异常类 就是我们自己知道异常了 但是机器并不会检测出异常 所以 人为的抛出了一个异常)

    菜鸟的羽毛

    之不是只要逻辑上 会有异常的地方都学要用到 try catch

    2016-08-09 16:42:08

    共 1 条回复 >

Java入门第三季

Java中你必须懂得常用技能,不容错过的精彩,快来加入吧

409780 学习 · 4339 问题

查看课程

相似问题