Monthly Archives: January 2016

Exception Handling in Java

Exception is an unexpected event that might occur at the time of executing the program. For example – if you are trying to open a file with name xyz.txt and that file does not exist on disk. At that time, you will get Exception viz. FileNotFoundException

Exception in Java
Exception Hierarchy

So if you think some part of code is risky and might throw Exception, you need to handle it so that program will continue to run in graceful manner.

In Java, we can use try…..catch construct to handle the Exceptions.

There are 2 types of Exceptions in Java.

  1. Checked Exception
  2. Unchecked Exception

Your code will not compile unless you handle checked exception. Unchecked exception happen at run time. For example – divide by zero exception.

throw and throws keyword in Java

throw keyword is used to throw custom exception. throws keyword is used when you do not want to handle the exception in current method. In this case, the caller of the method will have to handle the exception.

Below example illustrates how we can use try ….catch to handle exception.

package exceptions;

import org.testng.reporters.Files;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;

/**
 * Created by Sagar on 16-04-2016.
 */
public class TestExceptions {
    public static void main(String [] args) {
        try {
            Files.writeFile("shs",new File("c:\\xx"));
        } catch (FileNotFoundException ex) {
            System.out.println("File not found Exception occured");
            ex.printStackTrace();
        }catch (IOException ex){
            ex.printStackTrace();
        }finally {
            System.out.println("This finally block of code will be executed"
                    + " No matter if Exception is thrown or not");
        }

        System.out.println("Program continuing even after Exception comes");

        //Unchecked Exception - ArithmeticException
        //If you comment below line, program will exit with code 0
        System.out.println("this line throws " + 11/0);
    }
}

Here is the sample output of above example
This finally block of code will be executed No matter if Exception is thrown or not
Program continuing even after Exception comes

Process finished with exit code 1
File not found Exception occured
java.io.FileNotFoundException: c:\xx (Access is denied)
Exception in thread “main” java.lang.ArithmeticException: / by zero
This finally block of code will be executed No matter
if Exception is thrown or not
Program continuing even after Exception comes