Search code examples
javatry-catchcustom-exceptions

Cant pinpoint issue of when user inputs number less than 0 for my custom exception


Cant seem to figure this. If user inputs an invalid balance, how can i reprompt them to enter balance again and still continue my program?

  //EDITED STILL WONT WORK PROPERLY
 boolean again;
    while(again = true) 
    {
        try {

            // pass object to printwriter and pw to write to the file
            pw = new PrintWriter(fw);

            System.out.print("Input beginnning balance: ");
            balance = input.nextDouble();
            again = false;
            // pass user input to object
            AccountWithException acctException = new AccountWithException(fullName, balance, id, RATE);
            again = false;

            System.out.println(acctException.toString());

            // copy object to created file
            pw.println(acctException.toString());
            again = false; 

        // custom exception
        } catch (InvalidBalanceException e) {
            System.out.println(e.getMessage());
        } catch(FileNotFoundException e) {
            System.out.println(e.getMessage());
        } finally {
            pw.close();

Solution

  • you can throw Invalidbalanceexception and catch it in catch block like this

    try {
    
            // pass object to printwriter and pw to write to the file
            pw = new PrintWriter(fw);
    
            // pass user input to object
            AccountWithException acctException = new AccountWithException(fullName, balance, id, RATE);
    
            System.out.println(acctException.toString());
    
            // copy object to created file
            pw.println(acctException.toString());
    throw new InvalidBalanceException ();
    
            // custom exception if balance < 0
        } catch (InvalidBalanceException e) {
            System.out.println(e.getMessage());
            System.out.println("Re-enter balance: ");
            balance = input.nextDouble();
        } catch(FileNotFoundException e) {
            System.out.println(e.getMessage());
        } finally {
            System.out.println("Text file closed, program complete...");
            pw.close();
        }