问题
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/catch
statement:
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