I have two constructors :
protected WordStore() {
this.bigMap = new HashMap<>();
}
protected WordStore(String file) throws IOException {
this.bigMap = new HashMap<>();
String line = "";
try (BufferedReader bufferedReader = new BufferedReader(new FileReader(file));)
{
while ( (line = bufferedReader.readLine()) != null){
System.out.print(line);
}
}
catch (IOException e) {
System.out.println("The file could not have been loaded correctly");
}
}
The second one handles the IOexception
and it compiles correctly but when I try to initialise a new map from WordStore
:
WordStore store1 = new WordStore("text.txt");
I get a compiling error saying that the IOException
has not been handled. Obviously the constructors are in a different class than the store initialisation. This should be fairly easy to answer I'm just missing something.
throws
and catch
are different. When a method declares in its signature that it throws
an exception, the caller has to handle it by either rethrowing it back or by catching it.
protected WordStore(String file) throws IOException {
//doing something that can throw an IOException
}
//Caller handles it
try {
new WordStore("text.txt");
} catch (IOException ioex) {
//Handle the exception
}
//Or the caller (Assuming the caller is the main method) can throw it back
public static void main(String[] args) throws IOException {
new WordStore("text.txt");
}
Here, since you are already catching the IOException
, you can remove the throws
clause from the constructor.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments