Sumithra
Sumithra

Reputation: 6707

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

Upvotes: 0

Views: 223

Answers (3)

Michael Borgwardt
Michael Borgwardt

Reputation: 346317

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.

Upvotes: 1

Stephen C
Stephen C

Reputation: 718886

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.

Upvotes: 3

flash
flash

Reputation: 6810

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

Upvotes: 1

Related Questions