A method should usually perform its normal specified action. But
it often has cases, which are forbidden to be handled like this. In such
situations the method should throw an Exc
object
of a specific subclass.
So typically the necessity for throwing an
Exc
can be found out by testing a precondition.
You should test one precondition after another, always immediately
throwing a specific exception. It is understood, that these exceptions
should be specified in the throws clause of the method,
so that the programmer of the call can consider to change the call or to
make a handler for some of them. Here we complete the above example of
the bank account .
package org.company.project; import multex.Exc; import static multex.MultexUtil.create; class Account { final static long creditLimit = -5000; long balance = 0; /**Transfers the specified amount from this account * to the destination account. * @throws CreditLimitExc the new balance of the account would become * less than the creditLimit. */ public void transfer(final Account destination, final long amount) throws CreditLimitExc { //1. Checking for business rule violations: final long newBalance = balance - amount; if(newBalance < creditLimit){ throw create(CreditLimitExc.class, amount, creditLimit); } //2. Performing modifications: balance = newBalance; destination.balance += amount; } /**Taking {0} units from your account\t * will leave less than your credit limit {1} units on it. */ public static final class CreditLimitExc extends Exc {} }
Please note here, that for comfortably creating
a new parameterized exception object, as we cannot inherit parameterized
constructors in Java, we have to call the static generic factory method
MultexUtil.create
, and pass the class of the
desired exception, along with its parameters.