捕获其他类的异常

时间:2016-04-29 20:18:55

标签: java exception try-catch

我试图在我的AccountApplet类中摆脱这个错误,它是

AccountApplet.java:109: error: unreported exception EmptyFieldException; must be caught or declared to be thrown
      getAmount(wttf);
           ^

这是我的AccountApplet类的片段

  public void actionPerformed(ActionEvent e)
  {

    if (e.getSource() == dp)  //  Executes if deposit was clicked
    {
      //getAmount(dptf);
      status.setText("Deposit processed");

      refreshFields();

    }    

    if (e.getSource() == wt)  //  Executes if withdraw was clicked
    {
      getAmount(wttf);
      status.setText("Withdraw processed");

      refreshFields();
    }
  }  // End actionPerformed

  public void refreshFields()
  {
    NumberFormat fmt = NumberFormat.getCurrencyInstance();
    Account Account1 = new Account(1234, 1000.00);
    aitf.setText("" + Account1.getId());
    abtf.setText("" + fmt.format(Account1.getBalance()));
    // diplays accound id and balance in left text fields
    //should be called when the applet is first displayed and after each valid transaction
  }

  public double getAmount(JTextField tf) throws EmptyFieldException,
                                                NumberFormatException,
                                                NegativeAmountException
  {

    double withdraw;
    // try to parse 
    try {
        withdraw = Double.parseDouble(wttf.getText());
    } catch (Exception e) {
        // catch exception and do something about it  
        throw e;
    }
    // Next step


    return withdraw;
}  //  End       

这是我的帐户类

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;



public class Account extends Exception
{
  int id         = 1234;
  double balance = 1000.00;

  Account (int id, double balance)
  {
    id      = 1234;
    balance = 1000.00;
  }

  public int getId()
  {

    return id; 
  }

  public double getBalance()
  {
    return balance;   
  }

  public void setBalance(double balance) throws NegativeAmountException
  {

    // check for error and throw exception

  }

  public void deposit(double amount) throws NegativeAmountException
  {
    // check for error and throw exception
  }

  public void withdraw(double amount) throws NegativeAmountException,
                                             InsufficientFundsException
  {
    // check for error and throw exception
  }




}

1 个答案:

答案 0 :(得分:0)

您正在actionPerformed方法中调用getAmount(wttf);。 此方法抛出3个异常,因此您必须声明它们:public void actionPerformed(ActionEvent e) throws EmptyFieldException, NumberFormatException, NegativeAmountException。 但是,我仍然不确定为什么类帐户扩展了例外...