Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exception Handling and Opening a File?

Is it possible to use exceptions with file opening as an alternative to using .is_open()?

For example:

ifstream input;  try{   input.open("somefile.txt"); }catch(someException){   //Catch exception here } 

If so, what type is someException?

like image 639
Moshe Avatar asked Mar 12 '12 15:03

Moshe


People also ask

What is exception handling and file handling?

Exception Handling in File Processing. Exception Handling in File Processing. Finally. To handle exceptions, we can use the Try, Catch, and Throw keywords. These allowed us to perform normal assignments in a Try section and then handle an exception, if any, in a Catch block.

What is file handling and exception handling in Python?

Working with files will make your programs fast when analyzing masses of data. Exceptions are special objects that any programming language uses to manage errors that occur when a program is running.

How is error handling done while accessing files?

The header file “error. h” is used to print the errors using return statement function. It returns -1 or NULL in case of any error and errno variable is set with the error code. Whenever a function is called in C language, errno variable is associated with it.

What type of exception raise if error occur while opening a file?

In python programming , exceptions are raised when corresponding error occurs at run time but we can forcefully raise it using the keyword raise. we can also optionally pass in value to the exception to clarify why that exception was raised.


2 Answers

http://en.cppreference.com/w/cpp/io/basic_ios/exceptions

Also read this answer 11085151 which references this article

// 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

EDIT: catch exceptions by const reference 2145147

EDIT: removed failbit from the exception set. Added URLs to better answers.

like image 180
KarlM Avatar answered Sep 29 '22 15:09

KarlM


From the cppreference.com article on std::ios::exceptions

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.

like image 30
DumbCoder Avatar answered Sep 29 '22 13:09

DumbCoder