必须被抓住或宣布被抛出

时间:2014-03-01 21:22:45

标签: java exception

以下是我正在使用的代码

import java.util.*;

public class FinalExam
{
   public static void main (String[] args)
   {
   double amount = 0;
   SavingsAccount penny = new SavingsAccount("Penny Saved", 500.00, .05);
   Scanner input = new Scanner(System.in);
   System.out.print("Enter your deposit amount: ");
   try
   {
      amount = input.nextDouble();
      penny.deposit(amount);
   }
   catch(NegativeAmountException e)
   {
      System.out.println("NegativeAmountException: " + e.getMessage());
      System.exit(1);
   }
   System.out.print("Enter your withdraw amount: ");
   try
   {
      amount = input.nextDouble();
      penny.withdraw(amount);
   }
   catch(NegativeAmountException e)
   { 
      System.out.println("NegativeAmountException: " + e.getMessage());
      System.exit(1);
   }
   catch(InsufficientFundsException e)
   {
      System.out.println("InsufficientFundsException: " + e.getMessage());
      System.exit(1);
   }
}
}

当我尝试编译代码时,我收到错误消息:

FinalExam.java:8:错误:未报告的异常NegativeAmountException;必须被抓住或宣布被抛出    SavingsAccount penny = new SavingsAccount(“Penny Saved”,500.00,.05);                           ^ 1错误

我不确定如何修复此错误。任何建议都会有所帮助。

由于

1 个答案:

答案 0 :(得分:1)

您可以执行以下两项操作之一:将该行换行到try ... catch:

public static void main (String[] args)
{
   double amount = 0;
   SavingsAccount penny = null;
   try
   {
       penny = new SavingsAccount("Penny Saved", 500.00, .05);
       Scanner input = new Scanner(System.in);
       System.out.print("Enter your deposit amount: ");
       amount = input.nextDouble();
       penny.deposit(amount);
   }
   catch(NegativeAmountException e)
   {
      System.out.println("NegativeAmountException: " + e.getMessage());
      System.exit(1);
   }
   System.out.print("Enter your withdraw amount: ");
   try
   {
      amount = input.nextDouble();
      penny.withdraw(amount);
   }
   catch(NegativeAmountException e)
   { 
      System.out.println("NegativeAmountException: " + e.getMessage());
      System.exit(1);
   }
   catch(InsufficientFundsException e)
   {
      System.out.println("InsufficientFundsException: " + e.getMessage());
      System.exit(1);
   }
}

或者更改main()方法的签名,指定它可以抛出这种类型的异常(但这不是一个好主意)。