Exception:
RuntimeExceptions are unchecked Exceptions because compiler doesn't check to see whether the method handles (or) defines in the throws clause.
int i = (5/0);
This statement will produce a divide by zero (or) ArithmeticException
Here ArithmeticException "is a" RuntimeException. You don't have to (catch it(or) define it in the throws clause) during "compile time". During execution time you will get exception like
Exception in thread "main" java.lang.ArithmeticException: / by zero
at ExceptionTest.main(ExceptionTest.java:14)
try{
int i = (5/0);
catch(ArithmeticException e) {
System.out.println("ArithmeticException caught: " + e);
}
output:
ArithmeticException Caught: java.lang.ArithmeticException: / by zero
Hence the implication are "the catch block will always run when with RuntimeException is thrown".
"checkedException" are the ones which needs to be either declared in the throws clause (or) put in a try/catch block during compile time, failing to do this will result in a comiple-time error stating
Ouput:
ExceptionTest.java:12: unreported exception java.io.IOException; must be caught or declared to be thrown
c = (char) br.read();
^
Scenario-I
try{
do{
c = br.read();
System.out.println((char)c);
}while(c!=1);
}catch(IOException ex) {
System.out.println("IOException Caught: " + ex);
}
When you compile and execte this code what you get is plain output and no error. Even though "read()" method produces an IOException since it's inside a try block, the SOP statement inside the catch block will never be executed. This is because its a predefined method that throws an IOException which has to be inside a try block or defined in the throws clause.
Scenario-II
try{
throw new IOException("It's me IOException");
}catch(IOException ex) {
System.out.println("IOException Caught: " + ex);
}
Here we are throwing the IOException explicitly. Hence the catch blocks gets executed immeditely.
Ouput:
IOException Caught: java.io.IOException: It's me IOException