温馨提示×

CentOS下C++异常处理怎么写

小樊
39
2025-12-21 12:36:44
栏目: 编程语言

在 CentOS 下编写 C++ 程序时,异常处理通常使用 C++ 标准库中的 trycatchthrow 关键字。下面是一个简单的示例,展示了如何在 CentOS 下编写一个使用异常处理的 C++ 程序:

  1. 首先,使用文本编辑器(如 Vim、Nano 或 Gedit)创建一个名为 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 块中捕获它,然后输出错误信息。

  1. 保存文件并退出文本编辑器。

  2. 在终端中,使用 g++ 编译器编译 exception_example.cpp 文件:

g++ -o exception_example exception_example.cpp
  1. 运行编译后的程序:
./exception_example

现在,你可以尝试输入两个整数,包括第二个整数为零的情况。程序将正确处理异常并输出相应的错误信息。

注意:确保你的 CentOS 系统已安装了 g++ 编译器。如果尚未安装,可以使用以下命令安装:

sudo yum install gcc-c++

0