ubuntu

Ubuntu中C++异常处理怎么写

小樊
44
2025-05-06 13:00:33
栏目: 编程语言

在 Ubuntu 中使用 C++ 进行异常处理,主要依赖于 C++ 的异常处理机制,即 trycatchthrow 关键字。下面是一个简单的示例,展示了如何在 C++ 中使用异常处理:

#include <iostream>
#include <stdexcept> // 包含标准异常类

int divide(int numerator, int denominator) {
    if (denominator == 0) {
        throw std::invalid_argument("Denominator cannot be zero."); // 抛出异常
    }
    return numerator / denominator;
}

int main() {
    int num1 = 10;
    int num2 = 0;

    try {
        int result = divide(num1, num2); // 调用可能抛出异常的函数
        std::cout << "Result: " << result << std::endl;
    } catch (const std::invalid_argument& e) {
        std::cerr << "Caught an exception: " << e.what() << std::endl; // 捕获并处理异常
    } catch (...) {
        std::cerr << "Caught an unknown exception." << std::endl;
    }

    return 0;
}

代码解析:

  1. 抛出异常

    • divide 函数中,如果分母为零,我们使用 throw 关键字抛出一个 std::invalid_argument 异常。这是一个标准库提供的异常类,用于表示参数错误。
  2. 异常处理

    • main 函数中,我们使用 try 块包围可能抛出异常的代码。
    • 如果 divide 函数抛出异常,控制流会立即跳转到相应的 catch 块。
    • 我们捕获了 std::invalid_argument 类型的异常,并打印出异常信息。
    • 另外一个 catch (...) 块用于捕获所有其他类型的异常,确保程序不会因为未处理的异常而崩溃。
  3. 编译和运行

    • 使用 g++ 编译这个程序,可以使用以下命令:
      g++ -o exception_example exception_example.cpp
      
    • 然后运行生成的可执行文件:
      ./exception_example
      

异常处理是 C++ 中管理错误和异常情况的重要机制,它可以帮助你编写更健壮和可维护的代码。

0
看了该问题的人还看了