throw

suggest change
  1. When throw occurs 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('*'); }
    }
    
  2. When throw occurs in an expression without an operand, its effect is to rethrow the current exception. If there is no current exception, std::terminate is 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;
    }
    
  3. Dynamic exception specifications formerly used throw in function declarators. Non-empty specifications were removed in C++17. Empty throw() remained, equivalent to noexcept, until it was removed in C++20. Modern code can use noexcept to 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 exceptions
    

    A function declared noexcept calls std::terminate if an exception tries to escape it.

    Note that the first two uses of throw listed above constitute expressions rather than statements. (The type of a throw expression is void.) 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"));
    }
    

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents