I was wondering when it makes sense to throw checked exceptions in constructors. Until now I´ve always used RuntimeExceptions when validating constructor/method arguments. Short Pro/Cons I came up with:
Pro:
- Error recovery possible (catch)
Contra:
- Creating new instances requires a try-catch block -> ugly
For example:
/**
* Represents a savings-account.
* A savings-account must always have a positive balance.
*/
public class SavingsAccount extends Account {
/**
* Creates a new savings-account.
*
* @param id unique account identifier
* @param balance Initial account balance (in cents).
* Must be greater than zero (>0).
*/
public SavingsAccount(int id, int balance) throws AccountException {
super(id, balance);
if (getBalance() <= 0) {
// TODO: Throw exception.
}
}
// methods ...
I know that this is a very primitive example but it´s just for demonstration purposes. My intuition tells me that throwing a checked exception here makes sense, because the caller of the constructor may recover if the account is in an invalid state.
OR should I assume that the caller of the constructor knows its preconditions (from the documentation) and will always pass valid values? And if not, just throw a RuntimeException.
Any tips on what´s best for such scenarios?