Your exception handling is the problem. It's common, but bad code style: Whenever you catch an exception, the right move is to either deal with that exception, or, to ensure that you (re)throw some exception.
Log it, or print it? That is not handling an exception.
In this case, 'file not found' is not something you can be expected to handle; not unless you expand on what f1
is supposed to do (tip: Methods should be a bit more descriptive than that). Thus, throwing something is fair game. Furthermore, the very definition of f1
(presumably; that name is not particular enlightening and the method has no documentation) suggests that 'open this file' is a fundamental aspect of it, and therefore, throwing a FileNotFoundException
is fair as well.
Thus:
Best solution
public static FileInputStream f1(String fileName) throws IOException {
FileInputStream fis = new FileInputStream(fileName);
System.out.println("f1: File input stream created");
return fis;
}
public static void main(String[] args) throws Exception {
String fileName = "foo.bar";
System.out.println("main: Starting " + FileInputTest.class.getName()
+ " with file name = " + fileName);
try (InputStream in = f1(fileName)) {
// you must close any resources you open using a try-with-resources
// construct; you did not do that in your code, I fixed this.
}
}
NB: your psv main can (and generally should!) be declared to throws Exception
.
Alternate take
This one works in any scenario where you cannot throws
the exception, or if adding that the signature makes no sense because it reflects an implementation detail and not an inherent aspect of what the method is trying to do:
public static FileInputStream f1(String fileName) {
try {
FileInputStream fis = new FileInputStream(fileName);
System.out.println("f1: File input stream created");
return fis;
} catch (IOException e) {
throw new RuntimeException("Unhandled", e);
}
}
Naturally, this is only appropriate for situations where you really don't expect that exception to occur under normal circumstances. Otherwise, either throw that exception onwards or make your own exception type and throw that instead of RuntimeException
.
If you just need a ¯\(ツ)/¯ I don't really know what this means, I just want to move on and get rid of these exceptions solution: throw new RuntimeException("Uncaught", e);
is correct; e.printStackTrace();
is incorrect. Update your IDE's templates.