C++ の例外処理
こんな感じで、exceptionsを定義することで例外を発生させることができ、Javaのようにtry-catchで捕捉することができるらしい。
sample1.cpp
std::fstream file;
file.exceptions(std::fstream::failbit | std::fstream::badbit);
EOFでも例外が発生してしまう
一行ずつ読み込んで出力するだけの簡単なプログラムを作成。ファイルの読み込みはできたものの、EOFで例外が発生。
EOFのときにeofbitだけでなくfailbitも立ってしまっているのが原因。
sample1.cpp
# include <fstream>
# include <iostream>
# include <string>
int main(int argc, char *argv[])
{
std::fstream file;
file.exceptions(std::fstream::failbit | std::fstream::badbit);
try {
file.open("test.txt");
for (std::string buf; getline(file, buf);) {
std::cout << buf << std::endl;
}
file.close();
} catch (std::exception& e) {
std::cerr << "Exception" << std::endl;
}
return 0;
}
解決方法
failを検出したいのはファイルオープン失敗時のみなので、failの部分だけ自前で処理する(といっても判定して例外投げて終わり)1。
sample2.cpp
# include <fstream>
# include <iostream>
# include <string>
int main(int argc, char *argv[])
{
std::fstream file;
// failbitは自前で判定するようにした
file.exceptions(std::fstream::badbit);
try {
file.open("test.txt");
if (file.fail()) {
// TODO: お作法がわからないのでとりあえず実行時エラー
throw std::runtime_error("Cannot open file.");
}
for (std::string buf; getline(file, buf);) {
std::cout << buf << std::endl;
}
file.close();
} catch (std::exception& e) {
std::cerr << "Exception" << std::endl;
std::cerr << e.what() << std::endl;
}
return 0;
}
検証に使用した環境
- Windows 7 + Cygwin
- gcc (GCC) 7.4.0