-1

Here is the piece of code I'm working with

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);
   }
}
}

When I try to compile the code I get the error message:

FinalExam.java:8: error: unreported exception NegativeAmountException; must be caught or declared to be thrown SavingsAccount penny = new SavingsAccount("Penny Saved", 500.00, .05); ^ 1 error

I'm not really sure how to fix this error. Any advice will help.

Thanks

1 Answers1

1

You can do one of the two things: either wrap that line into 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);
   }
}

or to change the signature of main() method, specifying that it can throw this type of exception (but that is not a very good idea).

Ashalynd
  • 12,363
  • 2
  • 34
  • 37
  • When I do that I get 2 error messages: FinalExam.java:19: error: cannot find symbol penny.deposit(amount); ^ symbol: variable penny location: class FinalExam FinalExam.java:30: error: cannot find symbol penny.withdraw(amount); ^ symbol: variable penny location: class FinalExam 2 errors – user3369340 Mar 01 '14 at 21:33
  • right, because then it won't see the declaration. Changed the answer. – Ashalynd Mar 01 '14 at 21:45