The problem is surprisingly in the code you have not shown - your comment line :)
catch (IOException e) {
//do something
}
What exactly will you do in case of your readFromFile()
method does throw the exception?
1. Continue processing
Will you continue the processing with an empty map? So your readFromFile()
should then return an empty map and not throw the exception. (Or you may wrap the method into another one.)
public static void test1(String[] args) {
final Map<Integer, Integer> map = readFromFile();
final List<Integer> list = new ArrayList<>();
list.stream().map(x -> map.get(x)).collect(Collectors.toList());
}
2. Stop processing
Will you stop the further processing? Then simply return from the method. (Of course you should not just swallow the exception but to let the client method somehow know.)
public static void test1(String[] args) {
final Map<Integer, Integer> map;
try {
map = readFromFile();
}
catch (IOException e) {
// handle the exceptional situation
return; // or throw another exception, but leave the method
}
final List<Integer> list = new ArrayList<>();
list.stream().map(x -> map.get(x)).collect(Collectors.toList());
}
ADDED:
If you want your readFromFile()
method to throw an exception, think about wrapping the original exception into some your own exception. Of course it depends on where the method is in your application logic. If you consider it as a low-level method, IOException
quite suits the purpose. If you consider it more high-level, you should create your own exception reflecting the business logic of the method.
In both the cases do not forget to proper handle CLOSING of the input file in your readFromFile()
method, especially in the case of exception. You may use the Java 7 try-with-resources feature.