Unresolved compilation: Unhandled exception type IOException

安稳与你 提交于 2019-12-13 22:51:34

问题


When trying to write read an int from standard in I'm getting a compile error.

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
}

回答1:


in.read() can throw a checked exception of type 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.

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();
}



回答2:


The program doesn't have a bug.

The method read() requires you to catch an Exception in case something goes wrong.

Enclose the method inside a try/catchstatement:

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.



来源:https://stackoverflow.com/questions/7811468/unresolved-compilation-unhandled-exception-type-ioexception

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!