I am a Java beginner and knows that try...catch
statements are used to handle exceptions; means when an exception is thrown by try
block, catch
block is executed. So,my question is when I tried the following code (without try catch
) it throws a unreported IOException
in read()
method but when I use try catch
it works fine.
Why doesn't the control get transferred to catch statement when the above mentioned exception occurs in the try
block and exception occured
is printed?
here is my code:
class Test00 {
public static void main(String args[]) {
char ch;
try {
ch=(char)System.in.read();//here exception is thrown without using try..catch
System.out.println(ch);
} catch(Exception e) {
System.out.print("exception occured");
}
}
}
I think the compiler is saying to throw an exception,that's why the code worked with try catch.But why not the catch block is executed?is i am getting something wrong.