When to catch the Exception vs When to throw the Exceptions?

You should catch the exception when you are in the method that knows what to do.

For example, forget about how it actually works for the moment, let’s say you are writing a library for opening and reading files.

So you have a class, say:

public class FileInputStream extends InputStream {
    public FileInputStream(String filename) { }
}

Now, lets say the file doesn’t exist. What should you do? If you’re struggling to think of the answer, that’s because there isn’t one… the FileInputStream doesn’t know what to do about that problem. So it throws it up the chain, i.e.:

public class FileInputStream extends InputStream {
    public FileInputStream(String filename) throws FileNotFoundException { }
}

Now, lets say someone’s using your library. They might have code that looks like this:

public class Main {
    public static void main(String... args) {
        String filename = "foo.txt";
        try {
            FileInputStream fs = new FileInputStream(filename);

            // The rest of the code
        } catch (FileNotFoundException e) {
            System.err.println("Unable to find input file: " + filename);
            System.err.println("Terminating...");
            System.exit(3);
        }
    }
}

Here, the programmer knows what to do, so they catch the exception and handle it.

Leave a Comment