0

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.

datarell
  • 3
  • 2
  • 1
    `throw new AssertionError("Impossible because... ", e)` – Andy Turner May 12 '21 at 13:31
  • All kinds of issues can cause IOException here: file got deleted after you checked, some hardware issue actually causes a problem or you were using a file share and your network disconnected. – Generous Badger May 12 '21 at 13:36
  • FileNotFoundException != IOException. So, is your example really "Dead Code"? –  May 12 '21 at 13:36
  • Cross site duplicate: [How to deal with checked exceptions that cannot ever be thrown](https://softwareengineering.stackexchange.com/questions/122233/how-to-deal-with-checked-exceptions-that-cannot-ever-be-thrown) – Lino May 12 '21 at 13:38
  • You are all right, I didn't think about this. My manager check if a file exist by only using File.exists(), so the exception can still actually be thrown. Thank you all. – datarell May 12 '21 at 15:44

1 Answers1

0

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);
}
Andy Turner
  • 137,514
  • 11
  • 162
  • 243