throw
suggest change-
When
throwoccurs in an expression with an operand, its effect is to throw an exception. The exception object is initialized from the operand, which may copy or move it.void print_asterisks(int count) { if (count < 0) { throw std::invalid_argument("count cannot be negative!"); } while (count--) { putchar('*'); } } -
When
throwoccurs in an expression without an operand, its effect is to rethrow the current exception. If there is no current exception,std::terminateis called.try { // something risky } catch (const std::bad_alloc&) { std::cerr << "out of memory\n"; } catch (...) { std::cerr << "unexpected exception\n"; // hope the caller knows how to handle this exception throw; } -
Dynamic exception specifications formerly used
throwin function declarators. Non-empty specifications were removed in C++17. Emptythrow()remained, equivalent tonoexcept, until it was removed in C++20. Modern code can usenoexceptto state that a function does not propagate exceptions; there is no modern syntax for listing the exception types a function may propagate.void risky(); // may propagate exceptions void safe() noexcept; // must not propagate exceptionsA function declared
noexceptcallsstd::terminateif an exception tries to escape it.Note that the first two uses of
throwlisted above constitute expressions rather than statements. (The type of a throw expression isvoid.) This makes it possible to nest them within expressions, like so:unsigned int predecessor(unsigned int x) { return (x > 0) ? (x - 1) : (throw std::invalid_argument("0 has no predecessor")); }