未解决的编译:未处理的异常类型IOException

时间:2011-10-18 17:45:45

标签: java exception exception-handling

当我尝试从标准中读取一个int时,我遇到了编译错误。

System.out.println("Hello Calculator : \n");        
int a=System.in.read();

该程序抛出异常:

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
Unhandled exception type IOException at SamplePackege.MainClass.main(MainClass.java:15)

如何解决此错误?

我的代码:

try {
    Scanner sc = new Scanner(System.in);
    int a=sc.nextInt();
} catch (Exception e) {
    // TODO: handle exception
}

2 个答案:

答案 0 :(得分:2)

in.read()可以抛出IOException类型的已检查异常。

您可以阅读Java Here.

中的异常处理

您可以更改程序以抛出IOException,也可以将读取放在try catch块中。

try{
   int a=System.in.read();
catch(IOException ioe){
   ioe.printStackTrace();
}

public static void main(String[] args) throws IOException {
    System.out.println("Hello Calculator : \n");
    int a=System.in.read();
}

答案 1 :(得分:1)

该程序没有错误。

方法read()要求您在出现问题时抓住Exception

将方法包含在try/catch语句中:

try {
 int a = System.in.read();
 ...
}
catch (Exception e) {
 e.printStackTrace();
}

无论如何我强烈建议您使用文档和/或Java教程,其中明确说明了这些内容。不使用它们编程就没有意义了。你会省去很多麻烦,也可能是我们的时间。

相关问题