1
스트림에 문제가 발생하면 사용자 지정 예외를 throw 할 수있는 writeBinary (ostream) 메서드가있는 클래스 X가 있습니다.예외가있는 C++ 스트림 검사 오류
fstream 및 오류 검사에 올바른 방법은 무엇입니까?
여기 내 버전입니다. 뭔가 누락되었거나 오류가 발생했는지 알고 싶습니다.
ofstream ofs("X.binary.tmp");
if (!ofs) {
cerr << "Could not open file for writing";
throw runtime_error("Could not open file for writing");
}
try {
x.writeBinary(ofs);
} catch(CustomException& e) {
// remove the temporary file
int x = unlink("X.binary.tmp");
if (x) {
cerr << "Failed to remove file";
}
throw;
}
if (!ofs) { // is this check necessary?
int x = unlink("X.binary.tmp"):
if (x) {
cerr << "Failed to remove file";
}
throw std::runtime_error("Stream error");
}
rename("X.binary.tmp", "X.binary");
이 혼란 스러움을 단순화 할 수 있습니까?