How to use exception on open file in C++

2 Answers

0 votes
#include <iostream>
#include <fstream>

using std::cout;
using std::endl;

int main()
{
	std::ofstream ofs;

	ofs.exceptions(std::ios::failbit | std::ios::badbit);

	try {
		ofs.open("d:\abc.xyz", std::ios::out | std::ios::binary);
	}
	catch (std::ios_base::failure e) {
		cout << "Error open file: " << e.what() << endl;
		return 1;
	}

	ofs.close();

	return 0;
}

/*
run:

Error open file: ios_base::failbit set: iostream stream error

*/

 



answered Jun 19, 2018 by avibootz
0 votes
#include <iostream>
#include <fstream>

using std::cout;
using std::endl;

int main()
{
	std::ofstream ofs;

	ofs.exceptions(std::ifstream::failbit | std::ifstream::badbit);

	try {
		ofs.open("d:\abc.xyz", std::ios::out | std::ios::binary);
	}
	catch (const std::ifstream::failure &e) {
		cout << "Error open file: " << e.what() << endl;
		return 1;
	}

	ofs.close();

	return 0;
}

/*
run:

Error open file: ios_base::failbit set: iostream stream error

*/

 



answered Jun 19, 2018 by avibootz
...