1

Can anyone help me solve my problem. I am a beginner in Java programming. Previously when I did not declare throws IOException it gave me an error:

Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - unreported exception java.io.IOException; must be caught or declared to be thrown

The program is shown below:

import java.io.*;

public class addition {
    public static void main(String array[])throws IOException
    {
        InputStreamReader i = new InputStreamReader(System.in);
        BufferedReader b = new BufferedReader(i);
        System.out.println("Enter first number : ");
        int a1 = Integer.parseInt(b.readLine());
          System.out.println("Enter second number : ");
        int a2 = Integer.parseInt(b.readLine());
        int sum = a1 + a2 ;
        System.out.println("addition"+sum);
    }

}
Jonas Czech
  • 12,018
  • 6
  • 44
  • 65

1 Answers1

0

The BufferedReader function readLine() throws an IOException if there is an I/O failure while attempting to read from the input stream. In Java, you must use try catch statements to handle exceptions should they arise:

import java.io.*;

public class addition {
public static void main(String array[])throws IOException
{
    InputStreamReader i = new InputStreamReader(System.in);
    BufferedReader b = new BufferedReader(i);
    System.out.println("Enter first number : ");

    // Attempt to read in user input.
    try {
        int a1 = Integer.parseInt(b.readLine());
        System.out.println("Enter second number : ");
        int a2 = Integer.parseInt(b.readLine());
        int sum = a1 + a2 ;
        System.out.println("addition"+sum);
    }

    // Should there be some problem reading in input, we handle it gracefully.
    catch (IOException e) {
        System.out.println("Error reading input from user. Exiting now...");
        System.exit(0);
    }
}
}
hebrewduck
  • 66
  • 3