Is there any situations (in practice), that throwing Exception in catch block is useful?
For example
} catch (Exception e) {
String msg = "ErrorExample";
log.error(msg);
throw new RuntimeException(msg, e);
}
Is there any situations (in practice), that throwing Exception in catch block is useful?
For example
} catch (Exception e) {
String msg = "ErrorExample";
log.error(msg);
throw new RuntimeException(msg, e);
}
This specific trick of wrapping a checked exception into run-time exception is useful when you must implement an interface method that lacks a throws
declaration for the exception that you wish to throw. By wrapping the real exception into a RuntimeException
you effectively bypass the mechanism of checked exceptions, which may be the only thing available to you - for example, when you have no control of the interface that you are implementing.
This is not something you should do routinely, though, because it renders checked exceptions effectively useless. If you must take this route, throwing a more specific, custom, run-time exception is a better alternative, because your code becomes more explicit about the reason why you are doing the wrapping.
Whenever you trace something wrong going on, just revert back with an exception. Only thing you remember is, throw proper exception. That is absolutely normal.
For ex :
try {
// receive user age as input
// try to parse user input to integer
} catch (Exception e) {
throw new IllegalArgumentException("Please enter valid integer value", e);
}
There are many unforseen situations that you need to anticipate and create exceptions to handle them should they occur. e.g. you want a use to upload a photo in a registration form then they upload a word document or another file that is not an image file.
Catching and handling exceptions is guided by foresight that an unfavourable eventuality may occur and you plan adequately on how to handle it before it ever does so that it does not brick your application. This is just a drop in the ocean on the many ways that throwing Exception in a catch block is useful
Many frameworks and packages wrap internal exceptions with their own exception class. This is what inner exceptions are for. Whether to use checked or unchecked exceptions is an unrelated design decision and there are various views on this subject, see for instance [java checked vs unchecked exception explanation].1