Is it advisable as a practice to wrap an Unchecked exception into a Checked exception?
Why this question?
I am creating an API which wraps all the checked exceptions into an API specific checked exception. So I was wondering whether the unchecked exceptions can also be wrapped in checked exception.
Are there any advises on this? If they can be wrapped, it would be great if illustrated with a situation where it can make sense.
Checked exceptions should be used for conditions from which the caller can reasonably be recovered. By throwing a checked exception, you are forcing the caller to handle the exception in a catch clause or to propagate it outward. The API user can be recovered from the exceptional condition by catching the Exception and taking proper recovery steps.
For example, FileNotFoundException is a checked exception:
try {
FileInputStream fis = new FileInputStream(file);
} catch (FileNotFoundException e) {
// HANDLE THE EXCEPTION
}
Here even if the file is not found, continued execution of the application would be possible if the user has proper recovery steps in place (reading the file from a different location, etc.).
On the other hand, Runtime exceptions should be used to indicate that recovery is not possible and continued execution would do more harm. Many a times, runtime exceptions are used to indicate precondition violations: the contract that has been defined to use your API is violated by the client of your API.
For example, ArrayIndexOutOfBoundsException is a runtime exception:
int[] aa = new int[2];
int ii = aa[2]; // java.lang.ArrayIndexOutOfBoundsException
because the contract to access elements of an array says that array index must be between zero and the array length minus one, and we have violated that precondition above.
Again, suppose you are writing a class Address as below where the areaCode cannot be null. And if anybody creates an Address without an areaCode, it might do more harm in the future while using the Address. Here, you can use IllegalArgumentException (which is a runtime exception) to indicate that:
public class Address {
private String areaCode;
public Address(String areaCode) {
if (areaCode == null) {
throw new IllegalArgumentException("Area Code cannot be NULL");
}
this.areaCode = areaCode;
}
...
}
So, it is advisable to use checked exceptions wherever recovery is possible, and if recovery is not possible or if there is any precondition violation, it is good to use Runtime exception.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With