C++ 中的“throw 1”

`throw 1` in C++

我在 catch 块中看到了几个 C++ 示例 throw 1。试图找出它可能是什么,但总能找到一个带有异常对象或不带任何参数重新抛出异常的经典示例。

另外有时我可以在网上找到其他例子,同样没有解释:

throw 1
throw 2
throw -1

请告诉我这可能是什么意思。

Tell me please what it may mean.

这意味着您要抛出一个值为 12-1.

的 int 值

当然,没有任何进一步的细节,很难推断出其中的含义。

一个用例是报告函数的错误代码:

int returning_error_code() {
    try {
        stuff();
    } catch (int e) {
        return e; // return error code
    }

    return 0; // no error
}
throw 1
throw 2
throw -1

Tell me please what it may mean.

throw 抛出一个对象。 throw 1 如果类型 int 的值为 1,则抛出一个对象。我假设 reader 可以推断出其他两个的意思。

这是一种例外机制。可以捕获抛出的对象:

try {
    throw 1;
} catch (int e) {
    std::cout << "an integer was thrown and caught. here is the value: " << e;
}

I've seen throw 1 in catch block.

允许在异常处理程序中抛出。它与在处理程序外抛出的行为相同。

always found a classical example with exception object or rethrowing an exception without any argument.

这是抛出异常对象的情况。

可以抛出的对象类型没有限制。标准库遵循仅抛出 类 派生自 std::exception 的约定.建议在用户程序中遵循此约定。