Suppose there was a built-in JDK SizeLimitSubceededException
(I just learned that subceeded is the opposite of exceeded). Would your code, which checks the length of the SSN throw one exception - SizeLimitExceededException
- if the size exceeds the expected size, and another exception - SizeLimitSubceededException
- if the size subceeds the expected size?
This would be awkward:
- You would have to specify both exceptions in the
throws
clause of your method (assuming SizeLimitSubceededException
would be a checked exception, same as SizeLimitExceededException
).
- The caller of your method would have to handle both exceptions.
And what if the size is right, but something else is wrong - for example, the SNN contains non-digit characters? Would you throw a third exception for that?
My point is that you'd be better off throwing a single type of exception from the method that sets the SSN.
If you want this to be a checked exception (which I suggest, in order to force the caller to handle it), I suggest defining your own custom exception - perhaps InvalidSSNException
. This exception can have a constructor with several arguments - one of them the invalid SSN, another could be a boolean
that indicates if the exception was thrown due to incorrect length.
Then your custom exception can produce an error message that matches the reason to the failure:
If the entered SSN had the wrong length (and it doesn't matter if it's too long or too short), the message would specify the expected length (9).
If the entered SSN had the correct length, the message would specify the valid characters (digits only).
Example:
class Person {
...
public setSSN (String ssn) throws InvalidSSNException
{
if (ssn == null) {
throw new InvalidSSNException (ssn, false);
}
if (ssn.length() != 9) {
// exception thrown as a result of invalid length
throw new InvalidSSNException (ssn, true);
}
for (char c : ssn.toCharArray()) {
if (c < '0' || c > '9') {
// exception thrown as a result of invalid character
throw new InvalidSSNException (ssn, false);
}
}
this.ssn = ssn;
}
...
}