[Updated, sorry about the change but now to the real problem] I cannot include try-catch-loop there for the exception from the method getCanonicalPath(). I trie
You can provide a static method to initialize your static variable:
public static final String startingPath = initPath();
private static String initPath() {
try {
return new File(".").getCanonicalPath();
} catch (IOException e) {
throw new RuntimeException("Got I/O exception during initialization", e);
}
}
Or you can initialize your variable in a static block:
public static final String startingPath;
static {
try {
startingPath = new File(".").getCanonicalPath();
} catch (IOException e) {
throw new RuntimeException("Got I/O exception during initialization", e);
}
}
EDIT: In this case your variable is static
so there is no way to declare the exception thrown. Just for reference, if the variable is non-static
you could do this by declaring the thrown exception in the constructor, like so:
public class PathHandler {
private final String thePath = new File(".").getCanonicalPath();
public PathHandler() throws IOException {
// other initialization
}