+ 1
How can sololearn be so bad teaching the use of exceptions in c++?
First it's a shame to talk about exceptions and to throw only integers. At least throw an std::exception or std::runtime_exception. Then throwing and handling exceptions in the same function defeat the purpose of using exceptions. A good exemple would be to start with a function printing the division of two integers and using error codes to handle the divided by 0 error. Then explaining that if you want to return the result you cannot. And introduce exceptions and explain their advantages.
2 Réponses
+ 1
The example I propose would look like that:
int printDiv(int a, int b) {
if (b == 0) return -1;
cout << a / b;
return 0;
}
and then:
int div (int a, int b) {
if (b == 0) throw runtime_exception("divided by 0");
return a / b;
}
and the handling part:
int main() {
int result = printDiv(5, 0);
if (result != 0) {
cout << "error";
}
}
or
int main() {
try {
cout << div(5, 0);
}
catch (std::exception& e) {
cout << "error: " << e.what();
}
}
0
Will you post a good example or create a quiz about it?