在 CentOS 下编写 C++ 程序时,异常处理通常使用 C++ 标准库中的 try、catch 和 throw 关键字。下面是一个简单的示例,展示了如何在 CentOS 下编写一个使用异常处理的 C++ 程序:
exception_example.cpp 的文件:#include <iostream>
#include <stdexcept>
int main() {
int num1, num2;
int result;
std::cout << "Enter two integers: ";
std::cin >> num1 >> num2;
try {
if (num2 == 0) {
throw std::runtime_error("Division by zero is not allowed.");
}
result = num1 / num2;
std::cout << "Result: " << result << std::endl;
} catch (const std::runtime_error& e) {
std::cerr << "Error: " << e.what() << std::endl;
}
return 0;
}
在这个示例中,我们尝试将两个整数相除。如果第二个整数为零,我们抛出一个 std::runtime_error 异常,并在 catch 块中捕获它,然后输出错误信息。
保存文件并退出文本编辑器。
在终端中,使用 g++ 编译器编译 exception_example.cpp 文件:
g++ -o exception_example exception_example.cpp
./exception_example
现在,你可以尝试输入两个整数,包括第二个整数为零的情况。程序将正确处理异常并输出相应的错误信息。
注意:确保你的 CentOS 系统已安装了 g++ 编译器。如果尚未安装,可以使用以下命令安装:
sudo yum install gcc-c++