在C++ Linux系统中进行错误处理通常涉及以下几个方面:
open()
、read()
、write()
等函数在失败时会返回-1,并设置全局变量errno
来指示具体的错误类型。#include <fcntl.h>
#include <unistd.h>
#include <cerrno>
#include <cstring>
#include <iostream>
int main() {
int fd = open("nonexistent_file.txt", O_RDONLY);
if (fd == -1) {
std::cerr << "Error opening file: " << std::strerror(errno) << std::endl;
return 1;
}
// ... 使用文件描述符进行操作 ...
close(fd);
return 0;
}
try
、catch
和throw
关键字来捕获和处理异常。#include <stdexcept>
#include <iostream>
void mightFail() {
throw std::runtime_error("An error occurred");
}
int main() {
try {
mightFail();
} catch (const std::exception& e) {
std::cerr << "Caught exception: " << e.what() << std::endl;
return 1;
}
return 0;
}
SIGINT
)、非法指令(SIGILL
)等。可以使用signal()
或sigaction()
函数来设置信号处理函数。#include <csignal>
#include <iostream>
void signalHandler(int signum) {
std::cout << "Interrupt signal (" << signum << ") received.\n";
}
int main() {
signal(SIGINT, signalHandler);
std::cout << "Waiting for interrupt signal..." << std::endl;
while (true) {
// ... 主循环 ...
}
return 0;
}
assert()
宏:assert()
宏用于在调试阶段检查不应该发生的情况。如果断言失败,程序会终止并打印出错误信息。#include <cassert>
int main() {
int x = -1;
assert(x >= 0 && "x should be non-negative");
return 0;
}
#include <memory>
class File {
public:
explicit File(const char* filename) {
fd_ = open(filename, O_RDONLY);
if (fd_ == -1) {
throw std::runtime_error("Error opening file");
}
}
~File() {
if (fd_ != -1) {
close(fd_);
}
}
// ... 其他成员函数 ...
private:
int fd_;
};
int main() {
try {
std::unique_ptr<File> file(new File("nonexistent_file.txt"));
// ... 使用文件 ...
} catch (const std::exception& e) {
std::cerr << "Caught exception: " << e.what() << std::endl;
return 1;
}
return 0;
}
在实际编程中,通常会结合使用这些方法来进行错误处理,以确保程序的健壮性和可维护性。