Search code examples
javaexceptionmethodsfilenotfoundexceptionfileinputstream

How to write a method header that throws exception


"Given that FileInputStream’s constructor throws FileNotFoundException, which is a subclass of Exception, write the header for a public method named process that takes a String parameter and returns nothing, and whose body instantiates a FileInputStream object and does not contain a try-catch statement."

I know it's a too-simple question but I want to make sure I'm not messing up in a dumb way. Also, not sure whether to use FileNotFoundException or just Exception or IO, etc.

public process(String file) throws FileNotFoundException {

    FileInputStream file = new FileInputStream("stuff.txt");
}

Solution

  • What you have for the throws clause is good. Throwing IOException would not be terrible, but it's better to be specific. Calling code can still treat it as an IOException.

    Generally you shouldn't throw Exception except for special cases (Junit methods and similar situations where everything thrown will get caught by an exception handler), because it forces everything that calls it into the position of either handling Exception (where it may not be the appropriate place to do it, it is better to let most exceptions bubble up to one place where they can get handled uniformly) or also throwing Exception, which then puts other calling methods in the same position.

    Your method declaration is not valid because there's no return type. Methods that don't return anything are declared with a return type of void.

    Using the same name for a method parameter as for a local variable will not work, you should make those different. The constructor call should take the method parameter as an argument (instead of hard-coding a string literal). (+1 to geceo's answer for pointing that one out, I had missed that one.)

    As a suggestion, your code would be clearer if it used names that reflected the contents of the variables. Calling a FileInputStream file is not clear, it would be better to call it inputStream. Calling a String file is not clear, it would be better to call it filename.