输入输出异常处理

时间:2014-11-29 18:17:30

标签: java input exception-handling output

import java.io.IOException;
import java.util.Scanner;

public class Throwing {
    static void main(String[] args) throws IOException {
        int x = getInt();
        System.out.println(x);
    }

    public static int getInt() throws IOException {
        try {
            Scanner console = new Scanner(System.in);
            System.out.print("Type a number: ");
            int value = console.nextInt();
            System.out.println("You typed the integer ");
        }
        catch (IOException expection) {
            System.out.println("Not a integer");
        } 
        return 0;
    }
}  

程序是:如果你有整数,它会说它是整数,否则抛出IOException它不是整数。 我收到了这个错误:

Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - exception java.io.IOException is never thrown in body of corresponding try statement
at Throwing.getInt(Throwing.java:13)
at Throwing.main(Throwing.java:8)
Java Result: 1

3 个答案:

答案 0 :(得分:0)

这是因为scanner.nextInt()在int无效时不会抛出IOException,它会抛出InputMismatchException,因此您需要捕获InputMismatchException来检测无效int输入。

或者您可以使用Scanner.hasNextInt()来检测是否输入了有效的int而不是使用try-catch。

答案 1 :(得分:0)

try块中的代码永远不会抛出IOException。删除包装代码的try-catch块。它将返回InputMismatchException。

答案 2 :(得分:0)

要检查它是否为有效整数,如果不是则抛出IOException,请执行此操作

if(console .hasNextInt()){
   int value  = console .nextInt();
   System.out.println("You typed an integer:" + value);
}else{
   throw new IOException("It is not an integer");
}