Errors vs Exception
Errors should not be caught or handled.An Error is a subclass of Throwable that indicates serious problems that a reasonable application should not try to catch. Most such errors are abnormal conditions.
i.e AnnotationFormatError, AssertionError, LinkageError, VirtualMachineError
Example: OutOfMemoryError – Not much you can do as your program can no longer run.
Exceptions are often recoverable and even when not, they generally just mean an attempted operation failed, but your program can still carry on.
Example: IllegalArgumentException – Passed invalid data to a method so that method call failed, but it does not affect future operations.
What is difference between Checked Exception and Unchecked Exception?
The classes that extend Throwable class except RuntimeException and Error are known as checked exceptions e.g.IOException,SQLException etc. Checked exceptions are checked at compile-time.
The classes that extend RuntimeException are known as unchecked exceptions e.g. ArithmeticException,NullPointerException etc. Unchecked exceptions are not checked at compile-time.
Is it necessary that each try block must be followed by a catch block?
It is not necessary that each try block must be followed by a catch block. It should be followed by either a catch block OR a finally block. And whatever exceptions are likely to be thrown should be declared in the throws clause of the method.
Can finally block be used without catch?
Yes, by try block. finally must be followed by either try or catch
Is there any case when finally will not be executed?
finally block will not be executed if program exits(either by calling System.exit() or by causing a fatal error that causes the process to abort).
Can subclass overriding method declare an exception if parent class method doesn’t throw an exception ?
Yes but only unchecked exception not checked.
What is exception propagation ?
Forwarding the exception object to the invoking method is known as exception propagation. By default Unchecked Exceptions are forwarded in calling chain (propagated).
Method1() //Exception Occured Method2() Method3() main()
In the above example exception occurs in Method1() method where it is not handled,so it is propagated to previous Method2() method where it is not handled, again it is propagated to Method3() before main method where exception is handled.