Your exception handling is the problem.
Your exception handler says:
If a problem occurs, print some (but not all) debug info about it to standard error, and then keep on going with the code.
That is rarely the right move.
The best way to handle an exception is to actually handle it. Logging it isn't handling it.
If you can't handle it (and in this case, hey, how do you 'handle' a crucial file not being there? - You don't, that's not reasonable. Nobody expects you to write code to deal with half of your class files having been deleted either, right?) - then the right alternative is to just throw it onwards - add throws
to your method. And if you can't do that, the right 'uhhh I dunno' answer is this:
} (catch IOException e) {
throw new RuntimeException("unhandled", e);
}
and then the NPE would never have happened. Instead, you get proper info on the actual problem here, which is that strawberry.jpg
is not in the current working directory of the JVM process.
To get to the solution to your actual problem: If you have static resources, such as an image of a strawberry for your user interface, put then where your class files end up and use YourClass.class.getResource("strawberry.jpg")
to get at them; this uses the same mechanism java uses to find the class files of your app, i.e. it will even get them from within your jar files and such, and avoids any issues with current working directories.