There is one more option if the exception handling doesn't need to happen in the getContents
method -- add a throws
clause to the method to make the method throw an exception:
public static String getContents (File file)
throws IOException, FileNotFoundException {
This way, the code calling the method will handle the Exception
s rather than the method itself. There will be no need for try
/catch
blocks in that method, if the Exception
s are thrown up to the methods that called it.
This may or may not be the desired way to handle the situation, depending on how the method is expected to behave.
Edit
Upon second thought, making the method throw an exception may be a good idea. I think D.Shawley's comment I think sums it up well -- "exception handling should mean only handling the exception where it makes sense."
In this case, the getContents
method appears to get the contents of a specified File
, and returns a String
to the caller.
If the exception handling were to be performed in the getConents
method, the only way to communicate that an error has occurred is by returning some kind of pre-determined value, such as null
to the caller to inform that an error occurred.
However, by having the method itself throw an exception back to the caller, the caller can choose to react accordingly:
try {
String contents = getContents(new File("input.file"));
} catch (IOException ioe) {
// Perform exception handling for IOException.
} catch (FileNotFoundException fnfe) {
// Inform user that file was not found.
// Perhaps prompt the user for an alternate file name and try again?
}
Rather than having the setContents
method come up with its own protocol for notifying that an error occurred, it would probably be better to throw the IOException
and FileNotFoundException
back to the method caller, so the exception handling can be performed at a place where the appropriate alternate actions can take place.
Exception handling should only be performed if some meaningful handling can take place.