Skip to content

Exception Handling

Büşra Oğuzoğlu edited this page Jul 8, 2022 · 1 revision

File Reading:

Example code to read a text file named ’filename.txt’ line by line, and adding the contents to an array list:

public static ArrayList<String> readFile(){
    ArrayList<String> list = new ArrayList<String>();
    try{
        //the file to be opened for reading
        FileInputStream fis=new FileInputStream("filename.txt");
        Scanner sc=new Scanner(fis); //file to be scanned
        //returns true if there is another line to read
        
        while(sc.hasNextLine()){
            String line = sc.nextLine();
            list.add(line);
        }

        sc.close(); //closes the scanner
    }

    catch(IOException e){
        e.printStackTrace();
    }
    return list;
}

Try-catch statement in Java allows us to run a block of code and test it for the potential errors at the same time. This code is written in try block. If the error happens, code in the catch block will be executed.

We can optionally have a finally statement after catch, and it will be executed after try-catch, regardless of what happens.

If we do not use catch block, we have to add throws keyword to our method signature.

Clone this wiki locally