views:

40

answers:

3

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. What 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?

+1  A: 

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.

Michael Borgwardt
NumberFormatException is a Unchecked exception!
flash
There shouldn't be any negative for this. C'mon, it happens. You folks sometimes behave like a school examiner. +1 to counter it.
Adeel Ansari
@Adeel Ansari Agree! Downvote is a little bit too hard for this.
flash
+4  A: 

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.

Stephen C
+1  A: 

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
flash