CJCoding With Joseph
15free / daySign inCreate account
← Back to Question List

Select topics to narrow your question pool, then enable Random to jump to a random question matching your filters.

Topics:
C++ Quiz #154

What a Return Code Cannot Carry

hardExceptions

divideCode signals an error by returning -1; divideThrow throws instead. What does the output show that a return code loses and an exception keeps?

📄 Code

1#include <iostream>
2#include <stdexcept>
3 
4int divideCode(int a, int b) {
5 if (b == 0) {
6 return -1;
7 }
8 return a / b;
9}
10 
11int divideThrow(int a, int b) {
12 if (b == 0) {
13 throw std::invalid_argument("division by zero");
14 }
15 return a / b;
16}
17 
18int main() {
19 int code = divideCode(10, 0);
20 std::cout << "code result: " << code << "\n";
21 int alsoCode = divideCode(-5, 5);
22 std::cout << "code result: " << alsoCode << "\n";
23 try {
24 int value = divideThrow(10, 0);
25 std::cout << "throw result: " << value << "\n";
26 } catch (const std::exception& e) {
27 std::cout << "throw result: " << e.what() << "\n";
28 }
29 return 0;
30}