An Exception in a program is a situation by which the normal operation of program alters.If an exception occurs in a program that exception needs to be handled there itself.Otherwise our application becomes useless.As a programming language ,Java is having a number of exceptions defined . There are techniques to handle the Exceptions in Java
Exceptions in Java
There is a hierarchy for exceptions in Java.Everything is starting from Java.Lang.Object class.A schematic is shown below.
So the Exception hierarchy starts from the object class . The Throwable class inherits from Object class. Throwable has two subclasses , Exception and Error.The Throwable has some useful methods like printStackTrace() .These methods are widely using in Exception handling .
Exception Vs Error
If an error happens , it is not possible to recover the normal operation by handling them.But exceptions needs to be handled. Errors are not caused by program errors.Example of Error is stack overflow error.
Checked & Unchecked Exceptions
Checked Exceptions are sub classes of Exception class other than RuntimeException and its subclasses.In other words the Compiler can detect these exceptions .So the programmer will be forced to resolve the exception .
Example: InterruptedException needs to be handled in case if we are using Thread.sleep() method .
Unchecked Exceptions are exceptions happening at run time .The compiler cannot detect these exceptions.
Example :Null pointer Exception
try/catch in Java
Throws & Throw in Java
Custom exception in Java