我想捕获InputMismatchException,但它显示编译时错误

时间:2016-07-26 20:47:59

标签: java exception-handling compilation inputmismatchexception

编译时出现以下错误:

filimon.java:12: error: cannot find symbol
                }catch(InputMismatchException ime){
                       ^
  symbol:   class InputMismatchException
  location: class filimon
1 error

我的源代码是:

class filimon{
    public static void main(String[] args) {
        Scanner s=new Scanner(System.in);
        try{
            System.out.println("enter 2 integer values");
            int a=s.nextInt();
            int b=s.nextInt();
            System.out.println("value of a: "+a);
            System.out.println("value of b: "+b);
        }catch(InputMismatchException ime){
            System.err.println("please enter only number value");
        }
        catch(Exception e){
            System.err.println(e);
        }
    }//main
}//filimon

有什么问题?请帮帮我。

2 个答案:

答案 0 :(得分:0)

添加import java.util.InputMismatchException;

答案 1 :(得分:0)

Java无法找到InputMismatchException,因为它未导入。

InputMismatchException位于java.util

在文件顶部,写上

import java.util.InputMismatchException;

只导入例外,或

import java.util.*;

导入java.util中的所有内容。

作为旁注,

catch(Exception e)

不是个好主意。最好列出你想要捕获的每个异常,或者在它自己的catch块中,或者像这样:

catch(InputMismatchException|NoSuchElementException e){