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
那是因为当int无效时scanner.nextInt()
不会抛出IOException
,而是抛出InputMismatchException
,因此您需要捕获InputMismatchException
才能检测到无效的int输入。
或者,您可以Scanner.hasNextInt()
用来检测是否输入了有效的int,而不是使用try-catch。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句