Exception Handling (try...catch...finally)


The try...catch block is mainly use to handle exceptions in java as shown below.

First block : try

Second block : catch
Third block (optional): finally

Source: 
TestException.java


import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;


public class TestException {

    public static void main(String[] args) {
        try {
       
            Scanner scanner = new Scanner(new File("ccc"));
       
        } catch (FileNotFoundException exception) {


            exception.printStackTrace();
            System.out.println("Please contact sysadmin. 5111");


        } finally {

            //close any database or other resources, as this block will be executed irrespective of any exceptions or not in above 2 blocks
        }
   
        System.out.println("Thank you.");

    }

}



As the ccc file is not available the above program throws exception of FileNotFoundException type

No comments :

Post a Comment