Java – why should you try to throw an unchecked exception on a checked exception?
See English answers > the case against checked exceptions 32
If I have this method title, two exceptions will be thrown:
public static Optional<String> getFileMd5(String filePath) throws NoSuchAlgorithmException,IOException {}
Why should I replace them with a (less detailed) exception?
Solution
IOException is acceptable The caller cannot determine whether filepath exists and still exists when the method is executed, and your method must be able to signal a problem Throwing IOException in this case is a normal exception, but if you like runtime exceptions, you can wrap them in unchecked IOException Unchecked IO exceptions are as clear as checked ioexceptions What you will lose (or gain, depending on the point of view) is that you won't force the caller to deal with it
On the other hand, the nosuchalgorithmexception exception should be included in the runtime exception If your method uses a nonexistent algorithm, the caller cannot perform any operation If an exception occurs, it is obviously an error and should be signaled by a runtime exception Therefore, write your own runtime exception, wrap the original nosuchalgorithmexception (so that if you throw it, you won't lose the root cause of the problem), and don't disturb all callers of the code It will never happen
As for runtime and checked exceptions, it is mainly based on opinions, but the following points should be noted:
>AFAIK, there is no new Java API to use the checked exception For example, see Java Time, it will never throw checked exceptions, although old equivalents (such as dateformat) will throw checked exceptions > java is the only language to check exceptions. > The checked exception is not suitable for the functional idiom (lambda expression, stream, etc.) introduced in Java 8: no functional interface throws the checked exception
I think it can now be said that checking for exceptions is an interesting idea, but it turns out to be a bad idea You should prefer the unchecekd exception
Now, if your question is: how to throw an unchecked exception instead of checking for an exception, it's 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); } }