Java Exception Handling

Answer: In Java exception is an event that occurs during the execution of the program that disrupts the normal flow of instruction. In Java API throwable is a parent class of all Exception and Error classes. There are two types of exceptions  CheckedExceptions ( known as Compile-time exceptions) and  UncheckedExceptions ( known as runtimeExceptions) both type of exceptions extends Exception class.

CheckException: Checked exceptions must be explicitly caught or propagated as described in Basic try-catch-finally Exception Handling.
 Example:
import java.io.File;
import java.io.FileReader;
 public class FileDemo {
    public static void main(String args[]){                     
      File file=new File("E://file.txt");
      FileReader fr = new FileReader(file);
   }
 }

If you try to compile the above program you will get exceptions.”FileNotFoundException”, and which forces the programmer to catch them explicitly.

UncheckedException : Unchecked exception is an exception that occurs at time of execution, these include programming bugs such logic in error or in-proper used API
Example:If you have declared an array 5 and trying to call 6th element of the array the ArrayIndexOutOfBoundsExceptionexception .
public class ArrayOutBoundDemo{
     public static void main(String args[]){
      int num[]={1,2,3,4};
      System.out.println(num[5]);
   }
}
Errorindicate serious problems and abnormal conditions that most applications should not try to handle. Error defines problems that are not expected to be caught under normal circumstances by our program. For example memory error, hardware error, JVM error etc.

see in below diagram The exception hierarchy in Java:
We can handle the java exception in three way:

Throw: Sometime we might want to generate exception explicitly in our code, for example in a user authentication program we should throw exception to client if the password is null. throw keyword is used to throw exception to the runtime to handle it.

Throws: When we are throwing any exception in a method and not handling it, then we need to use throws keyword, We can provide multiple exceptions in the throws clause and it can be used with main() method.

Try-catch: Java try block is used to enclose the code that might throw an exception. It must be used within the method.
Syntax:
Try{
}catch(Exception e){
}finaly{
}
A catch statement involves declaring the type of exception you are trying to catch. If an exception occurs in try block.In finally block is optional and can be used only with try-catch block. Since exception halts the process of execution, we might have some resources open that will not get closed, so we can use finally block. finally block gets executed always, whether exception occurred or not

No comments: