TL ; DR:
When a method can't do what it was asked, it throws an exception. The code that called it catches the exception with try and catch.
public void Spend(int amount) {
if (amount > money) {
throw new ArgumentException("not enough money");
}
money -= amount;
}
try {
wallet.Spend(80);
} catch (ArgumentException e) {
Console.WriteLine("error: " + e.Message);
}
Full lesson:
Some requests can't be done. A wallet with 50 can't spend 80.
The method could return a special value, like -1. But the caller may forget to check it. Then the program goes on with a wrong number.
An exception is better. It is an error that the program can't miss.
Throwing an exception
throw new ArgumentException("not enough money")stops the method at once.- The lines after it don't run. So the wallet keeps its money.
ArgumentExceptionis C#'s built-in exception for a bad argument.- The text in the parentheses is the exception's message.
Catching it
- Put the call inside a
tryblock. - When the call throws, the rest of the
tryblock is skipped. - The
catchblock for that exception runs instead.eis the exception. e.Messageis its message.- Then the program goes on below the
catchblock.
An exception that nobody catches stops the whole program. C# prints it and the line where it happened.
Your task
A Wallet starts with 50. Its Spend method takes money out and returns what is left.
- In
Spend, throw anArgumentExceptionwhenamountis more thanmoney. Its message is"not enough money". - In the loop, call
Spendinside atryblock. Print what was spent and what is left. - Catch the exception. Print
error:and its message.
The loop tries to spend 20, then 40, then 30.
Expected output:
spent 20, 30 left
error: not enough money
spent 30, 0 leftFree plan: 30 tutor messages. Premium is unlimited.
