- Include required library files.
- Define a class named “NegativeAmount” and “InsufficientFunds”.
- Inside the “Account” class,
- Add the negative amount exception in the “deposit()” function.
- Add the negative amount and insufficient funds exception in the “withdraw()” function.
- Define a “main()” function to test the program to deposit and withdraw amounts.
- Create an object and test the deposit and withdraw using the appropriate function.
- Then print the result.
- Add the negative amount exception in the “deposit()” function.
- Add the negative amount and insufficient funds exception in the “withdraw()” function.
- Create an object and test the deposit and withdraw using the appropriate function.
- Then print the result.
Program to rewrite the given class “Account” that throws an appropriate exceptions and test the program to deposit and withdraw amounts are as follows,
Explanation of Solution
// Include required library files
#include <iostream>
using namespace std;
// Definition of class NegativeAmount
class NegativeAmount
{
};
// Definition of class insufficientFunds
class InsufficientFunds
{
};
// Definition of class Account
class Account
{
// Access specifier
private:
// Declaration of double variable
double balance;
// Access specifier
public:
// Definition of default constructor
Account()
{
// Assign 0 to balance
balance = 0;
}
// Definition of constructor to assign value
Account(double initialDeposit)
{
// Assign initialDeposit to balance
balance = initialDeposit;
}
// Definition of getBalance() function to return balance
double getBalance()
{
// Return balance
return balance;
}
// Definition of deposit() function to return new balance
// or throw NegativeAmount exception
double deposit(double amount) throw (NegativeAmount)
{
// Check amount is greater than 0
if (amount > 0)
// Condition is trur, compute balance
balance += amount;
// Otherwise
else
// Throw exception
throw NegativeAmount();
// Return balance
return balance;
}
// Definition of withdraw function to return new balance
// or throw NegativeAmount or InsufficientFunds
double withdraw(double amount) throw (NegativeAmount,
InsufficientFunds)
{
// Check amount is greater than balance
if (amount > balance)
// Throw insufficient exception
throw InsufficientFunds();
// Otherwise check amount is lesser than 0
else if (amount < 0)
// Throw negative amount execption
throw NegativeAmount();
// Otherwise
else
// Compute balance
balance -= amount;
// Return balance
return balance;
}
};
// Definition of main() function
int main()
{
// Creation of object and passing 100 to the constructor
Account a(100);
// Try block
try
{
// Call deposit() function to deposit 50
a.deposit(50);
// Call deposit() function to deposit 10
a.deposit(10);
// Call withdraw() function to deposit 220
a.withdraw(220);
// Call getBalance() function to get print balance amount
cout << a.getBalance() << endl;
}
// Catch block for negative amount
catch (NegativeAmount)
{
// Print the message regarding negative amount
cout << "You can't deposit or withdraw a negative amount."
<< endl;
}
// Catch block for insufficient funds
catch (InsufficientFunds)
{
// Print the message for insufficient funds
cout << "Insufficient funds for withdrawal." << endl;
}
// Declaration of character variable
char ch;
// Get an character
cin >> ch;
// Return 0
return 0;
}
Output:
Insufficient funds for withdrawal.
Want to see more full solutions like this?
Chapter 16 Solutions
Problem Solving with C++ (9th Edition)
- 2. Create one user object that invokes the default constructor.arrow_forwardclockType.h file provided //clockType.h, the specification file for the class clockType#ifndef H_ClockType#define H_ClockType class clockType {public: void setTime(int hours, int minutes, int seconds); //Function to set the time. //The time is set according to the parameters. //Postcondition: hr = hours; min = minutes; // sec = seconds // The function checks whether the values of // hours, minutes, and seconds are valid. If a // value is invalid, the default value 0 is // assigned. void getTime(int& hours, int& minutes, int& seconds) const; //Function to return the time. //Postcondition: hours = hr; minutes = min; // seconds = sec void printTime() const; //Function to print the time. //Postcondition: The time is printed in the form // hh:mm:ss. void incrementSeconds(); //Function to increment the time by one…arrow_forwardProblem C • -3: method consonants() had more than one loop • -3: method initials () had more than one loop • -3: at least one method used nested loopsarrow_forward
- C++ Test Reviewarrow_forwardC++arrow_forwardPLZ help with the following: True/False In java it is possible to throw an exception, catch it, then re-throw that same exception if it is desired GUIs are windowing interfaces that handle user input and output. An interface can contain defined constants as well as method headings or instead of method headings. When a recursive call is encountered, computation is temporarily suspended; all of the information needed to continue the computation is saved and the recursive call is evaluated. Can you have a static method in a nonstatic inner class?arrow_forward
- C# Write a program named TestScoreList that accepts eight int values representing student test scores. Display each of the values along with a message that indicates how far it is from the average. An example of how the results should be output is as follows: Test # 0: 89 From average: 6Test # 1: 78 From average: -5 using System;using static System.Console;class TestScoreList{static void Main(){// Write your main here}}arrow_forwardWrite a C++ program, you will create a class called Books to hold the information about the books in a library. The information required for each book is as follows Book Title Author name Publisher Publish year Subject Book ID (identical 5 digits’ number) Implement the following getBookInfo () member function that receives a pointer to a book and fills it up with user data. User input validation is necessary. The user should be properly prompted for each field. void getBookInfo (Books *b) Implement the following printBookInfo () member function. void printBookInfo (Books *b) Your function should print the book in the following format: Book Title : Object Oriented Programming Using C++ Author : Chris M. Szalwinski Publisher : Amazon Year : 2016 Subject : Computer Science Book Id : 00034 Note: You need to add required constructors/destructors, member functions or data members/variables in your program to complete its execution. //Missing lines of codes to be completed by the student }…arrow_forwardC# Program Create program that computes student average Requirements:1. Use inheritance2. Use exception handling if applicable3. Create a class student4. Use the constructor method to collect the student information: name, math, science and english grade (User should be able to input student info)5. Create a method that computes the average6. Create another method that outputs (similarly to) the ff. when calledName: AnnaMath: 92Science: 92English: 92Average: 927. Instantiate a Student object and utilize the defined methods.arrow_forward
- 1. void start() { } A a = new A(); B b = new B(); a.s(b); b = null; /* Line 5 */ a null; /* Line 6 */ System.out.println("start completed"); /* Line 7 */ When is the B object, created in line 3, eligible for garbage collection? after line 5 B after line 6 Cafter line 7 There is no way to be absolutely certain.arrow_forwardQuestion 3 } public class WeekDay { static void daysFromSunday(int day) { String dayName = ""; try { } } if (day > 7) { throw new Exception("Invalid Day! Too high!"); } else if(day < 1){ throw new Exception("Invalid Day! Too low!"); } switch(day){ case 1: dayName="Sun"; break; case 2: dayName="Mon"; break; case 3: dayName="Tue"; break; case 4: dayName="Wed"; break; } ▬▬ } case 5: dayName="Thu"; Dreak; case 5: dayName="Thu"; break; case 6: dayName="Fri"; break; default: dayName="Sat"; System.out.println(dayName); } catch (Exception excpt) { System.out.println("Oops"); System.out.println(excpt.getMessage()); }finally{ System.out.println("Done!"); public static void main(String[] args) { daysFromSunday(10); daysFromSunday(3); daysFromSunday(0); OOops Invalid Day! Too high! Tue Oops Invalid Day! Too low! OOops Invalid Day! Too high! Done! Tue Done! Oops Invalid Day! Too low! Done! O Oops Invalid Day! Too high! Done! Oops Invalid Day! Too high! Done! Oops Invalid Day! Too low! Done! O Oops…arrow_forwardWrite a class named StockPrices . The class constructor should accept an array of stock prices as its argument. The class should have a member function that returns the average of the stock prices. If any stock price in the array is negative or greater than 5000, the class should throw an exception. Demonstrate the class in a program. Ps: Using C++arrow_forward
- C++ for Engineers and ScientistsComputer ScienceISBN:9781133187844Author:Bronson, Gary J.Publisher:Course Technology PtrMicrosoft Visual C#Computer ScienceISBN:9781337102100Author:Joyce, Farrell.Publisher:Cengage Learning,Programming Logic & Design ComprehensiveComputer ScienceISBN:9781337669405Author:FARRELLPublisher:Cengage
- EBK JAVA PROGRAMMINGComputer ScienceISBN:9781337671385Author:FARRELLPublisher:CENGAGE LEARNING - CONSIGNMENT