unreported exception handling
I tried a simple code where user has to input a number. If user inputs a char it l produce numberformatexecption. That works fine. Now when i remove try catch block it shows error. 开发者_如何学JAVAWhat is the meaning of the error The code and error as follows
import java.io.*;
class execmain
{
public static void main(String[] args)
{
//try
//{
int a;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
a=Integer.parseInt(br.readLine());// ---------error-unreported exception must be caught/declared to be thrown
System.out.println(a);
//}
//catch(IOException e)
//{
//System.out.println(e.getMessage());
//}
}
}
Why this error comes?
The meaning of the error is that your application has not caught the IOException that might be thrown when you try to read characters from the input stream. An IOException is a checked exception, and Java insists that checked exceptions must either be caught or declared in the signature of the enclosing method.
Either put the try ... catch
stuff back, or change the signature of the main
method by adding throws IOException
.
The line:
a=Integer.parseInt(br.readLine());
will throw an IOException because br.readLine() throws this exception. Java will force you to either catch the exception explicitly, like your commented code block, or your method have to throw this exception explicitly like:
public static void main(String[] args) throws IOException
readLine()
throws IOException
which is a checked exception, which means it must bei either caught, or the method must be declared to throw it. Simply add the declaration to your main method:
public static void main(String[] args) throws IOException
You can also declare it as throws Exception
- for toy/learning programs that's just fine.
精彩评论