In Java, the base class of all the Exceptions are “java.lang.Throwable“. This class has two subclasses – “Error” and “Exception“.
java.lang.Error indicates serious problems that a reasonable application should not try to catch. Most such errors are abnormal conditions.
Examples : java.lang.ThreadDeath and java.lang.VirtualMachineError
try { throw new Error("This is the error"); } catch (Error e) { e.printStackTrace(); } // OR try { throw new Error("This is the error"); } catch (Throwable e) { e.printStackTrace(); }
java.lang.Exception :
The class “Exception” and its subclasses are a form of Throwable that indicates conditions that a reasonable application might want to catch.
All the subclasses of Exception forms the “Checked Exception” which must be caught by catch block.
Example : ClassNotFoundException, IOException
java.lang.RuntimeException:
This is the subclass of the Exception class. All the classes which extends this class are known as “UnChecked Exception“. This type of exception shows that there is some logical error in program.Unlike checked exception, it is not necessary to surround the code with try-catch block.
Example : ArithmeticException , NullPointerException
Question : Although all exceptions must be caught in catch block, then what is the need of checked and unchecked exception ? Why not all the exceptions are unchecked ?
Answer : How the programmer will come to know that which type of exception occur in API ? Hard way is when it occurs at run time and easy way is “when compiler complains that Exception is not handled properly”. It is very easy to handle the exception if API shows types of possible exception thrown (Checked Exception). it will make the programers life very easy.
Next Read – Read Exception chaining .
Leave a Reply