why BufferedReader class producing Exception at compile time not at the run time

1.7k Views Asked by At

I know Exceptions are occurs at run time not at the time of compilation.

so this code compiles successfully without any compile time Exception of type java.lang.ArithmeticException: / by zero but give an exception only at the run time

class divzero{
public static void main(String[] arg){
System.out.print(3/0);
}
}

but when i am using BufferedReader class it saying "unreported exception java.io.IOException; must be caught or declared to be thrown" when i am compiling the code given below. I think it should produce this exception at run time not at the time of compilation.because exceptions occurs at compile time.

import java.io.*;
class Bufferedreaderclass{

public static void main(String[] arg)
{
System.out.print("mazic of buffer reader \n Input : ");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String input;
input = br.readLine();
System.out.print("Your input is: "+input);
}
}

I know, i should throw an exception of IOException type but why? i want to know why "unreported exception java.io.IOException" at compile time not at run time.

please make it clear to me why it is behaving like this ?

2

There are 2 best solutions below

6
On BEST ANSWER

Since IOException is a checked exception, you must use either try...catch or 'throws`.

Usage of try...catch block is like below. It will handle runtime occurrence of IOException.

import java.io.*;
class Bufferedreaderclass{

public static void main(String[] arg)
{
    System.out.print("mazic of buffer reader \n Input : ");
    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    String input = "";
    try{
        input = br.readLine();
        System.out.print("Your input is: "+input);
    } catch (IOException e) {
    // do something useful with this exception
    }
}

For more information on using try...catch, see https://docs.oracle.com/javase/tutorial/essential/exceptions/handling.html

5
On

The signature of readLine is this

public String readLine() throws IOException

Therefore you have to handle the exception that it might throw. Add try/catch or add throws IOException to your method.

In java there are checked exceptions and unchecked exceptions. This is a checked exception and you have to deal with it in one way or another. ArithmeticException is an example of an unchecked exception.