You should catch an exception when you are in a method that knows what to do.
For example, forget about how it works at the moment, let's say you write a library to open and read files.
So you have a class, say:
public class FileInputStream extends InputStream {
public FileInputStream(String filename) { }
}
Now, let's say the file does not exist. What do you have to do? If you are struggling to come up with an answer because there is nobody ... FileInputStreamdoes not know what to do with this problem. Thus, he throws the chain, i.e.:
public class FileInputStream extends InputStream {
public FileInputStream(String filename) throws FileNotFoundException { }
}
, - . , :
public class Main {
public static void main(String... args) {
String filename = "foo.txt";
try {
FileInputStream fs = new FileInputStream(filename);
} catch (FileNotFoundException e) {
System.err.println("Unable to find input file: " + filename);
System.err.println("Terminating...");
System.exit(3);
}
}
}
, , .