← Back to Question List
C++ Code Walkthrough #131
Two Ways to Report a Bad Input
📄 Code
Read carefully — what does this print?1#include <iostream>2#include <stdexcept>34bool trySquareRoot(int value, int& result) noexcept {5 if (value < 0) {6 return false;7 }8 result = 0;9 while ((result + 1) * (result + 1) <= value) {10 result++;11 }12 return true;13}1415int squareRoot(int value) {16 if (value < 0) {17 throw std::domain_error("negative input");18 }19 int result = 0;20 while ((result + 1) * (result + 1) <= value) {21 result++;22 }23 return result;24}2526int main() {27 int inputs[] = {16, -4, 10};28 for (int value : inputs) {29 int root = 0;30 if (trySquareRoot(value, root)) {31 std::cout << "code style: " << root << "\n";32 } else {33 std::cout << "code style: failed\n";34 }35 try {36 int r = squareRoot(value);37 std::cout << "exception style: " << r << "\n";38 } catch (const std::domain_error& e) {39 std::cout << "exception style: " << e.what() << "\n";40 }41 }42 return 0;43}