java 未解析的编译:未处理的异常类型 IOException
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7811468/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Unresolved compilation: Unhandled exception type IOException
提问by mrHyman
When trying to write read an int from standard in I'm getting a compile error.
尝试从标准中写入读取 int 时,出现编译错误。
System.out.println("Hello Calculator : \n");
int a=System.in.read();
The program throws an exception:
程序抛出异常:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
Unhandled exception type IOException at SamplePackege.MainClass.main(MainClass.java:15)
How do I fix this error?
我该如何解决这个错误?
My Code :
我的代码:
try {
Scanner sc = new Scanner(System.in);
int a=sc.nextInt();
} catch (Exception e) {
// TODO: handle exception
}
回答by ScArcher2
in.read() can throw a checked exception of type IOException.
in.read() 可以抛出 IOException 类型的已检查异常。
You can read about Exception Handling in Java Here.
You can either change your program to throw an IOException, or you can put the read in a try catch block.
您可以更改程序以抛出 IOException,也可以将读取放入 try catch 块中。
try{
int a=System.in.read();
catch(IOException ioe){
ioe.printStackTrace();
}
or
或者
public static void main(String[] args) throws IOException {
System.out.println("Hello Calculator : \n");
int a=System.in.read();
}
回答by Hyman
The program doesn't have a bug.
该程序没有错误。
The method read()
requires you to catch an Exception
in case something goes wrong.
该方法read()
要求您捕获一个Exception
以防万一出现问题。
Enclose the method inside a try/catch
statement:
将方法括在try/catch
语句中:
try {
int a = System.in.read();
...
}
catch (Exception e) {
e.printStackTrace();
}
In any case I strongly suggest you to use documentation and/or Java tutorials, in which these things are clearly stated. Programming with out using them is just pointless. You will save yourself a lot of headaches, and probably also our time.
无论如何,我强烈建议您使用文档和/或 Java 教程,其中明确说明了这些内容。不使用它们进行编程是毫无意义的。您将省去很多麻烦,也可能省去我们的时间。