Saturday, 1 April 2017

Exception Handling in Java



Exception Handling in Java



An exception is a problem that arises during the execution of the program.

Let's see a practical example....

public class ExceptionExample {
    
    
    public static void main(String args[])
    {
        
       int a = 5,b=0,c;
             
       c = a/b; 
       
       System.out.println(c);
    }
    
    

}


As you can see, the value of the b variable is 0. If we divide any number with 0, the answer will be infinity. In Java an exception called ArithmeticException is thrown when this occurs.


When I executed this program, I got the following output:






So, we have to handle these exceptions so that the execution of our program does not disrupts or stops.

To handle the exception we have several options:
  1. Try and catch
  2. Throws
  3. Throw
  4. Finally

Try and catch

We surround the code which may throw an exception with try/catch block. In the try block we enclose the code which is prone to throw an exception. In the catch block we will declare the exception we are going to handle.

So let's understand this using the above example:


public class TryCatch {
    
    
     public static void main(String[] args) {
    
         int a = 5,b=0,c,d = 0;
             
         try
         {
             c = a/b; 
         }
         catch(ArithmeticException ae)
         {
         }
         d = a + b;
         
         System.out.println(d);
   
    }
    
}

Here is the output:



As you can see, because we have handled the exception using try/catch block the program execution didn't stop and printed the output.

Now, let's see how we can use throws and throw for exception handling.

Throws

This keyword is used to declare the particular exception you think that the method might throw.
It is used in the method declaration and you can specify as many exceptions you think the method will throw separated with a comma.

Let's see the syntax:


public void hello() throws XyzException, PqrException  //You can declare as many exceptions you want
{

}

This keyword can be used to mention that the method will throw an exception and if other programmer is calling this method then he has to handle this exception.


Throw

The throw keyword is used to explicitly throw an exception. The throw keyword is usually used for handling custom exceptions.


  1. In the following example, first of all, I created a custom exception called InvalidArrayElementException.
  2. Then I used the throw keyword to invoke the InvalidArrayElementException.
  3. Then the throws keyword mentions that the arrayElements() method will throw an exception. So, the method invoking this method has to handle this exception.
  4. Finally, we handle the exception in the main method using try/catch.




package exceptionhandling2;

import java.util.Scanner;


class InvalidArrayElementException extends Exception //Here I am creating my custom exception
{
    public InvalidArrayElementException(){
             System.out.println("Array element should not be smaller than 0.");
    }
}
public class ThrowsException {
    
    public static void main(String[] args)
    {
        ThrowsException te = new ThrowsException();
        try
        {
            te.arrayElements();
        }
        catch(InvalidArrayElementException ie)
        {
        }

    }   
    
    public void arrayElements() throws InvalidArrayElementException
    {
    
        int[] a = new int[5];
        int i;
        Scanner s = new Scanner(System.in);
        
        for(i=0;i<5;i++)
        {
           
           a[i] = s.nextInt();
           if(a[i]<0)
           {
               throw new InvalidArrayElementException();
           }
    
           
        }
        
        
        
    }
    
    

}

Here is the output:




Finally


This block does exactly what its name suggests. It executes regardless of exception occurrence.
It follows the try block or catch block.

It can be used to execute some cleanup code like closing a connection, stream, etc.

Let's see an example:


import java.util.Scanner;

public class FinallyException {
    
    public static void main(String[] args)
    {
    
        int a,b,c;
        Scanner s = new Scanner(System.in);
        a = s.nextInt();
        b = s.nextInt();
        try{
            c = a/b;
        }
        catch(ArithmeticException ae)
        {
             
            System.out.println("b should not be zero.");
            
        }
        finally
        {
            System.out.println("Therefore, the exception has been handled :)");
        
        }
    
    }
            
    
}

Here is the output:



So, with this exception handling in java is explained. If you have any doubt or want to make any improvements in this article please comment down below.






No comments:

Post a Comment

All About "static"

All About "static"

All About "static" Static means “no change”. In Java static is used with a variable or a class which is same for every...