Java Reference
In-Depth Information
505
public class BankAccount
{
public void withdraw(double amount)
{
if (amount > balance)
{
IllegalArgumentException exception
= new
IllegalArgumentException("Amount exceeds balance");
throw exception;
}
balance = balance - amount;
}
. . .
}
Actually, you don't have to store the exception object in a variable. You can just
throw the object that the new operator returns:
throw new IllegalArgumentException("Amount exceeds
balance");
When you throw an exception, execution does not continue with the next statement
but with an exception handler. For now, we won't worry about the handling of the
exception. That is the topic of
Section 11.4
.
When you throw an exception, the current method terminates immediately.
S
YNTAX
11.1 Throwing an Exception
throw
exceptionObject;
Example:
throw new IllegalArgumentException();
Purpose
To throw an exception and transfer control to a handler for this exception type