Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

10.9 What is the bank balance at the end of main? Why? public class Bank 1 doubl

ID: 3729552 • Letter: 1

Question

10.9 What is the bank balance at the end of main? Why? public class Bank 1 double balance; Bank (double b) balance - b; void debit (double amount) throws Exception f if (amount > balance) throw new Exception (); balance -- amount; public static void main(String [] args) throws Exception t Bank b -new Bank (5.2); try t b.debit (10.0); l catch (Exception e) balance) throw new Exception (); balance -- amount; public static void main(String [] args) throws Exception t Bank b -new Bank (5.2); try t b.debit (2.0); t catch (Exception e) 1 b.debit (1.0); Subtracting 1.0 does not cause an exception to be thrown, so the exception handling code does not execute. 3.2

Explanation / Answer

1)

If any clause included in the try clause generates an error, the code in the catch clause will be executed.

So here b.debit(10.0) generates error as amount>balance. Hence code in catch works.

The function void debit(double amount) throws Exception will throw exception.

So if we call b.debit(1.0) inside catch it keeps on throwing exceptions.

Hence take some appropriate steps for handling this exception

Hence this code can be modified as follows so that 1.0 is subtracted from balance.

public class Bank {
    double balance;
    Bank(double b)
    {
        balance=b;
    }
    void debit(double amount) throws Exception
    {
        if (amount>balance) throw new Exception();
        balance-=amount;
    }
    public static void main(String args[]) {
        Bank b=new Bank(5.2);
        try
        {
            b.debit(10.0);
        }
        catch(Exception e)
        {
            try{
            b.debit(1.0);
            }
            catch(Exception e1)
            {
              
            }
        }
            System.out.println("Balance = " + b.balance);
        }

        }

Output

Balance = 4.2

2)

Here also code is modified as


public class Bank {
    double balance;
    Bank(double b)
    {
        balance=b;
    }
    void debit(double amount) throws Exception
    {
        if (amount>balance) throw new Exception();
        balance-=amount;
    }
    public static void main(String args[]) {
        Bank b=new Bank(5.2);
        try
        {
            b.debit(2.0);
        }
        catch(Exception e)
        {
           try{
            b.debit(1.0);
           }
           catch(Exception e1)
           {
              
           }
        }
            System.out.println("Balance = " + b.balance);
        }

       
    }

Output

Balance = 3.2

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Chat Now And Get Quote