Question: deffernce between checked and unchecked exception in java
What is deffernce between checked and unchecked exception in java please explain by example
1)These are the exceptions which occur during the compile time of the program whereas Unchecked exceptions are the exceptions which occur during the run time of the program.
2)Checked exceptions must be explicitly caught or propagated as described in Basic try-catch-finally Exception Handling. Unchecked exceptions do not have this requirement. They don't have to be caught or declared thrown.
For more information, please go through the following link:
I strongly disagree. All exceptions occur at run time only.
The actual difference is a bit complicated.
Checked exceptions are the exceptions which are well known and likely to occur in some circumstance when the programmer uses some methods of the Java API. In such scenarios, the programmer must declare that his code can throw a checked exception at run time. This declaration is a compile - time check made by the java compiler for surity on java's robustness. If you are using methods which are likely to throw some checked Exception as specified in their throws clause, you must either handle them or specify in throws.
Specifying a throws is actually showing the compiler your awareness of the possibility that your method may throw an exception. At the same time, invokers of your method will find it easy to anticipate what all they need to handle as you are not handling but specifying in throws.
Thus we need to specify throws statement if we do not handle a checked exception.
However Runtime exceptions (Unchecked Exceptions) can occur any time and are actually coding bugs so should actually not be handled using catch block instead should be handled by writing bug-free code.
This can be a very harsh statement but still I stand to it:
"Runtime Exceptions should not be handled".
Instead they should be eradicated from code by changing code appropriately.