EXCEPTION HANDLING IN JAVA

 

Exception Handling in Java

                    The Exception Handling in Java is one of the powerful mechanism to handle the runtime errors so that the normal flow of the application can be maintained.


What is Exception Handling?

       Exception Handling is a mechanism to handle runtime errors such as ClassNotFoundException, IOException, SQLException, RemoteException, etc.


Advantage of Exception Handling:

                     The core advantage of exception handling is to maintain the normal flow of the application. An exception normally disrupts the normal flow of the application; that is why we need to handle exceptions.


Hierarchy of Java Exception classes:








Types of Java Exceptions:

                There are mainly two types of exceptions: checked and unchecked. An error is considered as the unchecked exception. However, according to Oracle, there are three types of exceptions namely;

  1. Checked Exception
  2. Unchecked Exception
  3. Error

Checked Exception:

                    The classes that directly inherit the Throwable class except RuntimeException and Error are known as checked exceptions. For example, IOException, SQLException, etc. 

                      Checked exceptions are checked at compile-time.

Unchecked Exception:

                        The classes that inherit the RuntimeException are known as unchecked exceptions. For example, ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException, etc. 

                      Unchecked exceptions are not checked at compile-time, but they are checked at runtime.

Java Exception Keywords:

                    Java provides five keywords that are used to handle the exception. The following table describes each.


KeywordDescription
tryThe "try" keyword is used to specify a block where we should place an exception code. It means we can't use try block alone. The try block must be followed by either catch or finally.
catchThe "catch" block is used to handle the exception. It must be preceded by try block which means we can't use catch block alone. It can be followed by finally block later.
finallyThe "finally" block is used to execute the necessary code of the program. It is executed whether an exception is handled or not.
throwThe "throw" keyword is used to throw an exception.
throwsThe "throws" keyword is used to declare exceptions. It specifies that there may occur an exception in the method. It doesn't throw an exception. It is always used with method signature.


Exception Handling Example

                    Let's see an example of Java Exception Handling in which we are using a try-catch statement to handle the exception.


  1. public class JavaExceptionExample{  
  2.   public static void main(String args[]){  
  3.    try{  
  4.       //code that may raise exception  
  5.       int data=70/0;  
  6.    }catch(ArithmeticException e){System.out.println(e);}  
  7.    //rest code of the program   
  8.    System.out.println("rest of the code...");  
  9.   }  
  10. }  


Output:

Exception in thread main java.lang.ArithmeticException:/ by zero
rest of the code...



TRY CATCH:

                   Java try block is used to enclose the code that might throw an exception. It must be used within the method.

If an exception occurs at the particular statement in the try block, the rest of the block code will not execute. So, it is recommended not to keep the code in try block that will not throw an exception.

Java try block must be followed by either catch or finally block.


Syntax of Java try-catch;

try{    
    //code that may throw an exception    
}catch(Exception_class_Name ref){}


EXAMPLE:


public class TryCatchExample1 {  
  
    public static void main(String[] args) {  
          
        int data=50/0; //may throw exception   
          
        System.out.println("rest of the code");  
          
    }  
      
}

Output:

Exception in thread "main" java.lang.ArithmeticException: / by zero
rest of the code


FINALLY:

                    Java finally block is a block used to execute important code such as closing the connection, etc.

Java finally block is always executed whether an exception is handled or not. Therefore, it contains all the necessary statements that need to be printed regardless of the exception occurs or not.

The finally block follows the try-catch block.


EXAMPLE:

  1. class TestFinallyBlock {    
  2.   public static void main(String args[]){    
  3.   try{    
  4. //below code do not throw any exception  
  5. int data=25/5;    
  6.    System.out.println(data);    
  7.   }    
  8. //catch won't be executed  
  9.   catch(NullPointerException e){  
  10. System.out.println(e);  
  11. }    
  12. //executed regardless of exception occurred or not  
  13.  finally {  
  14. System.out.println("finally block is always executed");  
  15. }    
  16.     
  17. System.out.println("rest of php code...");    
  18.   }    
  19. }   


Output:

Java finally block


THROW:

                    The Java throw keyword is used to throw an exception explicitly.

We specify the exception object which is to be thrown. The Exception has some message with it that provides the error description. These exceptions may be related to user inputs, server, etc.

We can throw either checked or unchecked exceptions in Java by throw keyword. It is mainly used to throw a custom exception. We will discuss custom exceptions later in this section.

syntax

  1. throw new exception_class("error message");  

EXAMPLE:


  1. public class TestThrow1 {   
  2.     //function to check if person is eligible to vote or not   
  3.     public static void validate(int age) {  
  4.         if(age<18) {  
  5.             //throw Arithmetic exception if not eligible to vote  
  6.             throw new ArithmeticException("Person is not eligible to vote");    
  7.         }  
  8.         else {  
  9.             System.out.println("Person is eligible to vote!!");  
  10.         }  
  11.     }  
  12.     //main method  
  13.     public static void main(String args[]){  
  14.         //calling the function  
  15.         validate(13);  
  16.         System.out.println("rest of the code...");    
  17.   }    
  18. }    

Output:

Java throw keyword


THROWS:

                    The Java throws keyword is used to declare an exception. It gives an information to the programmer that there may occur an exception. So, it is better for the programmer to provide the exception handling code so that the normal flow of the program can be maintained.

                 Exception Handling is mainly used to handle the checked exceptions. If there occurs any unchecked exception such as NullPointerException, it is programmers' fault that he is not checking the code before it being used.

syntax

  1. return_type method_name() throws exception_class_name{  
  2. //method code  
  3. }  

EXAMPLE:


  1. import java.io.IOException;  
  2. class Testthrows1{  
  3.   void m()throws IOException{  
  4.     throw new IOException("device error");//checked exception  
  5.   }  
  6.   void n()throws IOException{  
  7.     m();  
  8.   }  
  9.   void p(){  
  10.    try{  
  11.     n();  
  12.    }catch(Exception e){System.out.println("exception handled");}  
  13.   }  
  14.   public static void main(String args[]){  
  15.    Testthrows1 obj=new Testthrows1();  
  16.    obj.p();  
  17.    System.out.println("normal flow...");  
  18.   }  
  19. }  


Output:

exception handled
normal flow...


Comments