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 ?
Since
IOException
is a checked exception, you must use eithertry...catch
or 'throws`.Usage of
try...catch
block is like below. It will handle runtime occurrence ofIOException
.For more information on using
try...catch
, see https://docs.oracle.com/javase/tutorial/essential/exceptions/handling.html