The exception of IO is valid. The caller cannot be sure that the Path file exists and will exist when the method is executed, and your method should be able to signal a problem. An IOException is a common exception that you have selected in this case, although you can wrap it inside a UncheckedIOException if you prefer runtime exceptions. The IO exception thrown will be as clear as the checked IOException. What you lose (or gain, depending on your point of view) is that you cannot force the caller to work with him.
The NoSuchAlgorithmException exception, on the other hand, must be included in the runtime exception. The caller has no right to do anything if your method uses an algorithm that does not exist. This is clearly an error if this exception occurs, and errors should be signaled by runtime exceptions. So write your own runtime exception that wraps the original NoSuchAlgorithmException (so that you don't lose the root cause of the problem if you ever throw it), and don't bother all the code that calls you with an exception that should never .
Regarding runtime compared to checked exceptions, this is mainly an opinion-based question, but a few things should be noted:
- AFAIK, the new Java API does not use checked exceptions. For example, see Java.time, which never throws checked exceptions, although the old equivalent (like DateFormat) throws checked exceptions
- Java is the only language that has checked exceptions.
- Checked exceptions do not correspond to well-functioning idioms (lambda expressions, threads, etc.) introduced in Java 8: no functional interface throws a checked exception.
I think now it is safe to say that the checked exceptions were an interesting idea, but which turned out to be a bad one. You should prefer to exclude fuzzy exceptions.
Now, if your question is: how to throw excluded exceptions rather than checked exceptions, this is pretty simple:
public static Optional<String> getFileMd5(String filePath) { try { // your original code } catch (IOException e) { throw new UncheckedIOException(e); } catch (NoSuchAlgorithmException e) { throw MyCustomCryptoException(e); } }
source share