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