Java Reference
In-Depth Information
An exception thrown from a constructor has the same effect on the client as an exception
thrown from a method. So the following attempt to create an invalid
ContactDetails
object
will completely fail; it will
not
result in a
null
value being stored in the variable:
ContactDetails badDetails = new ContactDetails("", "", "");
Code 12.7
The constructor of the
ContactDetails
class
/**
* Set up the contact details. All details are trimmed to remove
* trailing white space. Either name or phone must be non-blank.
* @param name The name.
* @param phone The phone number.
* @param address The address.
* @throws IllegalStateException If both name and phone are blank.
*/
public
ContactDetails(String name, String phone, String address)
{
// Use blank strings if any of the parameters is null.
if
(name ==
null
){
name =
""
;
}
if
(phone ==
null
) {
phone =
""
;
}
if
(address ==
null
) {
address =
""
;
}
this
.name = name.trim();
this
.phone = phone.trim();
this
.address = address.trim();
if
(
this
.name.length() == 0 &&
this
.phone.length() == 0) {
throw new
IllegalStateException(
"Either the name or phone must not be blank."
);
}
}
12.5
Exception handling
The principles of exception throwing apply equally to both unchecked and checked exceptions,
but the rules of Java mean that exception handling becomes a requirement only with checked
exceptions. A checked exception class is one that is a subclass of
Exception
but not of
RuntimeException
. There are several more rules to follow when using checked exceptions,
because the compiler enforces checks both in a method that throws a checked exception and in
any caller of that method.
Search WWH ::
Custom Search