When you specify the method "throws (an) Exception" the compiler expects an exception to occur, so he can "throw" it back to the caller. But when you handle the Exception using the "try/catch" blocks, no exception can be "thrown" back to the caller of the method (because the exception has been handled already).
A "correct" version of you code would be either -
public AnimalStats(){
simulator = new Simulator();
try{
fos = new FileOutputStream("AnimalStats.csv",true);
pw = new PrintWriter(fos);
}
catch(IOException e) {
System.out.println("Error has been caught!");
e.printStackTrace();
}
}
or
public AnimalStats() throws IOException{
simulator = new Simulator();
fos = new FileOutputStream("AnimalStats.csv",true);
pw = new PrintWriter(fos);
}
There is a major difference though!
In the first approach the method handles the Exception within itself. It "doesn't want" an exception to occur and be returned to the function who called AnimalStats().
As opposed to the first approach, in the latter we declare the method throws (an) IOException
. We do not intend to handle the exception within the method and we "throw" the exception back to the function who called AnimalStats() and let them handle it.