Reputation: 10531
To work with multiple file reading and output, what's the best way to handle exceptions in try catch block.
try{
BufferReader br1 = new BufferReader(new InputStreamReader(fileName1));
BufferReader br2 = new BufferReader(new InputStreamReader(fileName2));
}catch(FileNotFoundException e){
System.err.println("Not found file " + fileName1);
System.err.println("Not found file " + fileName2);
}
If there is only one file not found, then the warning message isn't quite right. If I create another try catch block, then it can solve the problem, but it seems awkward. What's the best way in this situation? Thanks.
Upvotes: 0
Views: 2035
Reputation: 1577
Create a createBufferedReader(String fileName)
method then you won't have that problem.
Sample:
private BufferReader createBufferedReader(String fileName) {
BufferReader br = null;
try {
br = new BufferReader(new FileReader(fileName));
return br;
} catch(FileNotFoundException e) {
System.err.println("Not found file" + fileName);
}
return null;
}
Upvotes: 2
Reputation: 144
I would create a helper method to create a BufferedReader
and call it twice.
Upvotes: 0
Reputation: 11403
I find it sensible to just separate the two try
-catch
blocks, no more, no less.
The solution provided by Nappa The Saiyan does its dirty job, but wrapping a piece of functionality in a method should imply that either the method succeeds or fails throwing an exception. It shall not print to stderr
. Throwing the exception again in the wrapper method will give the original problem again.
Really, go separate the try
-catch
blocks. And if you have n > 2
filenames, just write a for loop on an array of filenames and customize your error message so that it prints the number of the file that could not be read. Then you'll have a single try
-catch
.
Upvotes: 0