Skip to content
Advertisement

Java. Handle dead code (by application logic) in catch block

I have the following piece of code.

Path path = Paths.get(file.getAbsolutePath());
ByteArrayResource resource = null;
try {
    resource = new ByteArrayResource(Files.readAllBytes(path));
} catch (IOException e) {
    // DEAD CODE.
    // file existance is checked by resource manager
}

Is there a better way to handle the dead catch? The “file” variable is loaded by a resource manager, that already handle the case of a file not found (by throwing an exception itself). This is “dead code” only because of application logic, if it was not for the manager doing the check, this would have not been “dead code”.

The alternative I can think of, is to create a custom DeadCodeException() (extending RuntimeException()) and throw it whenever a case like this appear. This would not cause a NullPointerException() on “resource”, in case in the future the manager logic changes.

How can I handle this case using good code standards?

Edit:

Thank you everyone. Apparently I made a mistake here. As @GenerousBadger and @RandomCoder_01 have remarked, IOExceptionI() is not a FileNotFoundException(), so it can still be thrown given the right (wrong?) circustances.

I will use AssertionError() in similar situations, by as for this one, I have to handle the exception.

Advertisement

Answer

The compiler doesn’t know as much as you. It can’t know that you’ve already checked that the file exists (and, of course, the file could be deleted in between the existence check and use).

You should indicate to the compiler (and readers) that things are really broken if you reach that point. A standard way to do this would be something like:

} catch (IOException e) {
    throw new AssertionError("Should not reach here, already checked for existence!", e);
}
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement