Ubuntu下C++如何进行异常处理

2172
2025/4/12 9:32:55
栏目: 编程语言
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

在 Ubuntu 下使用 C++ 进行异常处理,你需要遵循以下步骤:

  1. 引入头文件:在你的 C++ 源代码中,需要引入 <stdexcept> 头文件,它包含了标准异常类的定义。
#include <stdexcept>
  1. 抛出异常:当程序遇到错误时,可以使用 throw 关键字抛出一个异常。你可以使用标准异常类(如 std::runtime_error、std::invalid_argument 等),也可以自定义异常类。
if (error_condition) {
    throw std::runtime_error("An error occurred");
}
  1. 捕获异常:使用 try 和 catch 块来捕获和处理异常。try 块包含可能抛出异常的代码,catch 块包含处理异常的代码。
try {
    // Code that may throw an exception
} catch (const std::exception& e) {
    // Code to handle the exception
    std::cerr << "Exception caught: " << e.what() << std::endl;
}

下面是一个简单的示例,演示了如何在 Ubuntu 下使用 C++ 进行异常处理:

#include <iostream>
#include <stdexcept>

int main() {
    int divisor;
    std::cout << "Enter a number to divide by: ";
    std::cin >> divisor;

    try {
        if (divisor == 0) {
            throw std::invalid_argument("Division by zero is not allowed");
        }
        int result = 100 / divisor;
        std::cout << "Result: " << result << std::endl;
    } catch (const std::invalid_argument& e) {
        std::cerr << "Error: " << e.what() << std::endl;
    }

    return 0;
}

在这个示例中,我们尝试将 100 除以用户输入的数字。如果用户输入 0,我们将抛出一个 std::invalid_argument 异常,并在 catch 块中捕获和处理它。

辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读: ubuntu lmgrd对系统性能有影响吗