Account::Account(double newBalance)//Set construtor
{
if (newBalance >= 0)
{
balance = newBalance;
// cout << "Your balance is: " << balance << endl;
}
elsethrow invalid_argument("New Accounts should have a positive balance.");
}
And for some reason is not working. First, I had an else statement setting the balance to 0 (zero) then I decided to add the throw statement. The constructor works as long as the newBalance is positive but once I enter a negative number I get a Runtime error to appear. I tried adding the header #include<stdexcept> but it didn't work.
I went back over the textbook and this "throw" exception is a pretty easy to use tool.
I read about try blocks and this is not a try block. In the textbook there are several examples using if/else statements that throw exception and they are caught right in the same line I have listed here.
The string should display in the console when the constructor uses a negative amount. I thought about what you said and modified the constructor to this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
Account::Account(double newBalance)//Set construtor
{
if (newBalance >= 0)
{
balance = newBalance;
cout << "Your balance is: " << balance << endl;
}
else
balance = 0;
throw invalid_argument("New Accounts should have a positive balance.");
}
If the balance was less than 0, the else statement should set it to 0 and throw the exception. Still didn't work.
If balance is a member of Account there is no point in setting it to zero just before you throw. The throw will make the object never to be created so balance will never be used anyway.
You also introduced a bug in you latest code. The throw is placed outside the else part and will always happen. Use brackets if you want to have multiple statements in the else part.
Edit: To further clarify: Every thrown exception needs to be caught. If you don't catch it, the program will crash. When an exception is thrown in a manner such as the 'working' example you presented, it unwinds the call stack until it finds a catch statement that can handle it's exception. Since there was nothing to catch it in the function, it returns to wherever called the function, and tries to find something to catch it there. Again, if it doesn't find anything, it returns again, all the way up until it eventually reaches main()
, at which point if main doesn't catch it, it goes up the call stack again, and at this point the program crashes. The program does not resume after the throw statement, it resumes after the catch statement.
Peter,
balance is a member of Account. I need to practice more with exceptions so I am going to handle this execption using an else statement setting balance to 0 if the amount is less than 0.
Intrexa,
thanks for your explanations. I was going to try your suggestion but I copied the example from the book and it is close to 200 lines of code so I just going to concentrate on my homework first and then I'll do some more research on exceptions.