I'm new to writing Java code and I'm having a hard time understand how throwing works. I keep getting errors when I compile a portion of my code that has to do with throwing. How do I fix these?
My code:
class BankAccount {
public String name;
public double balance;
public BankAccount(String name, double balance) throws NegativeAmountException {
this.name = name;
this.balance = balance; // set name and balance
// throw exception if balance is negative
if (balance < 0) { // make sure balance is not negative
throw new NegativeAmountException(
"Can not create an account with a negative amount.");
}
}
public BankAccount(String name) throws NegativeAmountException {
this(name, 0); // set name and use 0 balance
}
// update balance by adding deposit amount
// make sure deposit amount is not negative
// throw exception if deposit is negative
public void deposit(double amount) {
if (amount > 0) {
this.balance += amount;
} else {
throw new NegativeAmountException("Deposit amount must not be negative");
}
}
throws NegativeAmountException
// update balance by subtracting withdrawal amount
// throw exception if funds are not sufficient
// make sure withdrawal amount is not negative
// throw NegativeAmountException if amount is negative
// throw InsufficientFundsException if balance < amount
public void withdraw(double amount) throws InsufficientFundsException,
NegativeAmountException {
if (amount > getBalance()) {
throw new InsufficientFundsException(
"You do not have sufficient funds for this operation.");
} else if (amount < 0) {
throw new NegativeAmountException(
"Withdrawal amount must not be negative.");
} else {
this.balance -= amount;
}
}
// return current balance
public double getBalance() {
return this.balance;
}
// print bank statement including customer name
// and current account balance
public void printStatement() {
System.out.println("Balance for " + this.name + ": " + getBalance());
}
}
The errors I get are:
BankAccount.java:26: error: illegal start of type
throws NegativeAmountException
^
BankAccount.java:26: error: ';' expected
throws NegativeAmountException
^