Exceptions
Some errors only show up while the program runs. An index is too big. A number that should be positive is negative. A function that hits such a problem cannot return a normal answer, because there is none. C++ handles this with exceptions.
When something goes wrong, the code throws an exception. This stops the normal flow and sends an error message up to code that can deal with it. If nothing deals with it, the program stops.
You can see this with a vector's .at(). It reads an element like [ ], but it first checks the index. If the index is too big, it throws an exception:
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int> prices = {10, 20, 30};
cout << prices.at(1) << "\n";
cout << prices.at(7) << "\n";
cout << "Done" << "\n";
return 0;
}
Output:
20
terminate called after throwing an instance of 'std::out_of_range'
prices.at(1) printed 20. Then prices.at(7) threw an exception of type out_of_range. Nothing caught it, so the program stopped, and Done was never printed.
try and catch
To handle an exception, put the risky code in a try block and add a catch block after it:
#include <iostream>
#include <vector>
#include <stdexcept>
using namespace std;
int main() {
vector<int> prices = {10, 20, 30};
try {
cout << "Looking up..." << "\n";
cout << prices.at(7) << "\n";
cout << "This line never runs" << "\n";
} catch (const out_of_range& e) {
cout << "Caught: " << e.what() << "\n";
}
cout << "Done" << "\n";
return 0;
}
Output:
Looking up...
Caught: vector::_M_range_check: __n (which is 7) >= this->size() (which is 3)
Done
When .at(7) throws, the rest of the try block is skipped. The program jumps to the catch block for that type of exception. e is the exception, and e.what() returns its message. The & avoids a copy, and const means the catch block will not change e. After the catch block, the program goes on as normal, so this time Done is printed.
The exception types, like out_of_range and runtime_error, come from #include <stdexcept>.
Throwing your own exceptions
Your own functions can throw too. Write throw, then an exception with your message:
#include <iostream>
#include <stdexcept>
using namespace std;
void setAge(int age) {
if (age < 0) {
throw runtime_error("Age cannot be negative");
}
cout << "Age set to " << age << "\n";
}
int main() {
try {
setAge(30);
setAge(-5);
setAge(40);
} catch (const runtime_error& e) {
cout << "Error: " << e.what() << "\n";
}
return 0;
}
Output:
Age set to 30
Error: Age cannot be negative
setAge(-5) threw, so setAge(40) never ran.
Why not just return a special value like -1 for "error"? Because the caller can forget to check it, and the program goes on with a wrong value. An exception cannot be missed. Either some code catches it, or the program stops with a clear error.
Put the catch where you can do something useful about the problem, for example show a message or use a default value.
In the exercise, make a divide function throw a runtime_error when the divisor is zero, so that main can catch it.