runtime_error怎么throw
时间: 2023-08-26 11:05:31 浏览: 69
在 C++ 中,可以使用 `throw` 关键字来抛出异常。可以抛出许多不同类型的异常,其中包括 `runtime_error`。以下是一个简单的示例,演示如何使用 `throw` 抛出一个 `runtime_error` 异常:
```c++
#include <iostream>
#include <stdexcept>
using namespace std;
int divide(int a, int b) {
if (b == 0) {
throw runtime_error("Attempted to divide by zero!"); // 抛出 runtime_error 异常
}
return a / b;
}
int main() {
int a = 10;
int b = 0;
try {
int c = divide(a, b); // 调用 divide 函数
cout << c << endl;
} catch (exception& e) {
cout << "Exception caught: " << e.what() << endl; // 捕获并处理异常
}
return 0;
}
```
在上面的代码中,我们定义了一个名为 `divide` 的函数,该函数尝试将两个整数相除。如果第二个整数为零,则会抛出一个 `runtime_error` 异常。在 `main` 函数中,我们通过调用 `divide` 函数来尝试执行除法运算,并使用 `try`、`catch` 块来捕获并处理可能会抛出的异常。如果异常被抛出,则 `catch` 块将输出异常消息。在本例中,输出将是:
```
Exception caught: Attempted to divide by zero!
```
希望这可以回答您的问题。