Java Reference
In-Depth Information
IllegalArgumentException
An IllegalArgumentException is thrown programmatically if an argument passed into a
method is not valid, where validity is based on the business logic of your application and
the specifi c behavior of the method. For example, the following HomeForSale class declares
a constructor with a parameter of type double that needs to be a percentage between 0 and
1 . The constructor throws an IllegalArgumentException on line 7 when the argument is
out of this range:
1. public class HomeForSale {
2. private String agent;
3. private double commission;
4.
5. public HomeForSale(String agent, double commission) {
6. if(commission < 0.0 || commission > 1.0) {
7. throw new IllegalArgumentException(
“commission must be between 0 and 1”);
8. }
9. this.agent = agent;
10. this.commission = commission;
11. }
12. }
Be careful not to use an assertion in this situation. We may want the commission to
be between 0 and 1 , but we cannot assert this because the argument passed in can be any
value. Throwing an IllegalArgumentException is a good way to communicate to the
calling method that the data they provided is not valid.
IllegalStateException
An IllegalStateException is thrown programmatically when a method is invoked and the
program is not in an appropriate state for that method to perform its task. This typically
happens when a method is invoked out of sequence, or perhaps a method is only allowed to
be invoked once and an attempt is made to invoke it again.
For example, suppose you develop an order processing system and an attempt is made
to ship an order before the shipping address has been input. The shipOrder method could
throw an IllegalStateException , as the following code demonstrates:
1. public class CustomerOrder {
2. private String address;
3.
4. public void shipOrder() {
5. if(address == null) {
6. throw new IllegalStateException(
Search WWH ::




Custom Search