首页 > 文章列表 > Linux C++如何进行错误处理

Linux C++如何进行错误处理

492 2025-04-07

Linux C++如何进行错误处理

本文探讨在Linux环境下,C++程序的几种有效错误处理策略。

一、返回错误码

函数可通过返回特定错误码指示错误发生。这些码通常定义于头文件,例如errno.h

#include 
#include 
#include 

int main() {
    FILE* file = fopen("nonexistent.txt", "r");
    if (file == nullptr) {
        std::cerr << "Error opening file: " << strerror(errno) << std::endl;
        return 1; // 返回非零值表示错误
    }
    fclose(file);
    return 0; // 返回0表示成功
}

二、异常处理

C++的异常处理机制,利用trycatchthrow关键字捕获和处理异常。

#include 
#include 
#include 

void readFile(const std::string& filename) {
    std::ifstream file(filename);
    if (!file.is_open()) {
        throw std::runtime_error("无法打开文件: " + filename);
    }
    // ...读取文件内容...
}

int main() {
    try {
        readFile("nonexistent.txt");
    } catch (const std::exception& e) {
        std::cerr << "异常捕获: " << e.what() << std::endl;
        return 1;
    }
    return 0;
}

三、断言

assert宏用于调试阶段验证程序假设。若条件不成立,程序终止并输出错误信息。

#include 
#include 

int divide(int numerator, int denominator) {
    assert(denominator != 0 && "除数不能为零");
    return numerator / denominator;
}

int main() {
    int result = divide(10, 0); // 将触发断言失败
    return 0;
}

四、日志记录

日志记录跟踪程序运行时的错误和其他重要事件。可以使用或第三方日志库,如log4cpp、spdlog。

#include 
#include 
#include 

void logError(const std::string& message) {
    std::ofstream logFile("error.log", std::ios::app);
    if (logFile.is_open()) {
        logFile << message << std::endl;
        logFile.close();
    }
}

int main() {
    FILE* file = fopen("nonexistent.txt", "r");
    if (file == nullptr) {
        logError("打开文件错误: " + std::string(strerror(errno)));
        return 1;
    }
    fclose(file);
    return 0;
}

五、智能指针

智能指针(如std::unique_ptrstd::shared_ptr)自动管理资源,降低内存泄漏风险。

#include 
#include 

class Resource {
public:
    Resource() { /* ... */ }
    ~Resource() { /* ... */ }
    Resource(const Resource&) = delete;
    Resource& operator=(const Resource&) = delete;
};

void useResource() {
    std::unique_ptr res(new Resource());
    // 使用res...
} // res在此自动释放资源

int main() {
    useResource();
    return 0;
}

实际编程中,可根据需求选择或组合使用以上方法,提升程序健壮性和可维护性。