Learn Java Tutorial for Beginners (Video), Part 34: Handling Exceptions

Exceptions are a major part of the Java language; so much so that you can't write very much code without at least having to handle some of them. In this tutorial we'll get started with Exceptions, and I'll also give you some tips for taking the sting out of those big red error messages that so horrify beginners.

When the video is running, click the maximize button in the lower-right-hand corner to make it full screen.



Code for this tutorial:

demo1/App.java:

 

package demo1;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;



public class App {

    public static void main(String[] args) throws FileNotFoundException {
        
        File file = new File("test.txt");
        
        FileReader fr = new FileReader(file);
    }

}

 

demo2/App.java:

 

package demo2;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;

public class App {

    public static void main(String[] args) {
        File file = new File("test.txt");

        try {
            FileReader fr = new FileReader(file);
            
            // This will not be executed if an exception is thrown.
            System.out.println("Continuing ....");
        } catch (FileNotFoundException e) {
            System.out.println("File not found: " + file.toString());
        }

        System.out.println("Finished.");
    }

}

 

demo3/App.java:

 

package demo3;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;

public class App {

    public static void main(String[] args) {
        try {
            openFile();
        } catch (FileNotFoundException e) {
            // PS. This message is too vague : )
            System.out.println("Could not open file");
        }
    }

    public static void openFile() throws FileNotFoundException {
        File file = new File("test.txt");

        FileReader fr = new FileReader(file);

    }

}