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

File Handling


File Writer 


How to use existing Java API for writing data to external file for persistance.
Source: TestFileWriter.java


import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

public class 
TestFileWriter {
    public static void main(String[] args) {
    try {
            FileWriter writer = new FileWriter("c:/citydata.txt", true); //set true for append mode
            BufferedWriter bufferedWriter =new BufferedWriter(writer);
            bufferedWriter.write("Tokyo");
            bufferedWriter.write(",");
            bufferedWriter.write("New York");
            bufferedWriter.write(",");
            bufferedWriter.write("Colombo");
            bufferedWriter.write(",");
            bufferedWriter.write("Korea");
            bufferedWriter.write("\n");

            bufferedWriter.flush();
            bufferedWriter.close();
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}

Output
After running above program check for creation of c:/citydata.txt with following contents


Tokyo, New York, Colombo, Korea
=================================================


File Reader 


How to use existing Java API for reading data from external file.
Source: TestFileReader.java

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;

public class 
TestFileReader {
    public static void main(String[] args) {
        File file = new File("c:/citydata.txt");
        try {
            Scanner scan = new Scanner(file);
            while (scan.hasNext()) {
                System.out.println(scan.nextLine());
            }       
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

    }
}

Output
Tokyo, New York, Colombo, Korea