Is it possible to use exceptions with file opening as an alternative to using .is_open()
?
是否可以使用带有文件打开的异常作为使用.is_open()的替代方法?
For example:
例如:
ifstream input;
try{
input.open("somefile.txt");
}catch(someException){
//Catch exception here
}
If so, what type is someException
?
如果是,什么类型是例外?
3 个解决方案
#1
30
http://en.cppreference.com/w/cpp/io/basic_ios/exceptions
http://en.cppreference.com/w/cpp/io/basic_ios/exceptions
Also read this answer 11085151 which references this article
也请阅读参考本文的答案11085151
// ios::exceptions
#include <iostream>
#include <fstream>
using namespace std;
void do_something_with(char ch) {} // Process the character
int main () {
ifstream file;
file.exceptions ( ifstream::badbit ); // No need to check failbit
try {
file.open ("test.txt");
char ch;
while (file.get(ch)) do_something_with(ch);
// for line-oriented input use file.getline(s)
}
catch (const ifstream::failure& e) {
cout << "Exception opening/reading file";
}
file.close();
return 0;
}
Sample code running on Wandbox
在Wandbox上运行的示例代码
EDIT: catch exceptions by const reference 2145147
编辑:通过const引用2145147捕获异常
EDIT: removed failbit from the exception set. Added URLs to better answers.
编辑:从异常集中删除故障位。添加url以获得更好的答案。
#2
0
From the cppreference.com article on std::ios::exceptions
关于std: ios::例外。
On failure, the failbit flag is set (which can be checked with member fail), and depending on the value set with exceptions an exception may be thrown.
在失败时,设置failbit标志(可以与member fail一起检查),并根据带有异常的值设置抛出异常。
#3
0
I think while (!file.eof())
statement should not be in the try
scope..
我认为while (!file.eof()语句不应该在try范围内。
#1
30
http://en.cppreference.com/w/cpp/io/basic_ios/exceptions
http://en.cppreference.com/w/cpp/io/basic_ios/exceptions
Also read this answer 11085151 which references this article
也请阅读参考本文的答案11085151
// ios::exceptions
#include <iostream>
#include <fstream>
using namespace std;
void do_something_with(char ch) {} // Process the character
int main () {
ifstream file;
file.exceptions ( ifstream::badbit ); // No need to check failbit
try {
file.open ("test.txt");
char ch;
while (file.get(ch)) do_something_with(ch);
// for line-oriented input use file.getline(s)
}
catch (const ifstream::failure& e) {
cout << "Exception opening/reading file";
}
file.close();
return 0;
}
Sample code running on Wandbox
在Wandbox上运行的示例代码
EDIT: catch exceptions by const reference 2145147
编辑:通过const引用2145147捕获异常
EDIT: removed failbit from the exception set. Added URLs to better answers.
编辑:从异常集中删除故障位。添加url以获得更好的答案。
#2
0
From the cppreference.com article on std::ios::exceptions
关于std: ios::例外。
On failure, the failbit flag is set (which can be checked with member fail), and depending on the value set with exceptions an exception may be thrown.
在失败时,设置failbit标志(可以与member fail一起检查),并根据带有异常的值设置抛出异常。
#3
0
I think while (!file.eof())
statement should not be in the try
scope..
我认为while (!file.eof()语句不应该在try范围内。