Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why are C++ STL iostreams not "exception friendly"?

I'm used to the Delphi VCL Framework, where TStreams throw exceptions on errors (e.g file not found, disk full). I'm porting some code to use C++ STL instead, and have been caught out by iostreams NOT throwing exceptions by default, but setting badbit/failbit flags instead.

Two questions...

a: Why is this - It seems an odd design decision for a language built with exceptions in it from day one?

b: How best to avoid this? I could produce shim classes that throw as I would expect, but this feels like reinventing the wheel. Maybe there's a BOOST library that does this in a saner fashion?

like image 452
Roddy Avatar asked Jul 05 '10 14:07

Roddy


People also ask

Can C++ handle asynchronous exceptions?

The C++ standard supports synchronous exception handling with a termination model. Termination means that once an exception is thrown, control never returns to the throw point. Exception handling is not designed to directly handle asynchronous exceptions such as keyboard interrupts.

Does C++ support exception handling?

Exception handling in C++ consist of three keywords: try , throw and catch : The try statement allows you to define a block of code to be tested for errors while it is being executed. The throw keyword throws an exception when a problem is detected, which lets us create a custom error.

Do we have exceptions in C?

The C programming language does not support exception handling nor error handling. It is an additional feature offered by C. In spite of the absence of this feature, there are certain ways to implement error handling in C. Generally, in case of an error, most of the functions either return a null value or -1.


1 Answers

  1. C++ wasn't built with exceptions from day one. "C with classes" started in 1979, and exceptions were added in 1989. Meanwhile, the streams library was written as early as 1984 (later becomes iostreams in 1989 (later reimplemented by GNU in 1991)), it just cannot use exception handling in the beginning.

    Ref:

    • Bjarne Stroustrup, A History of C++: 1979−1991
    • C++ Libraries
  2. You can enable exceptions with the .exceptions method.

// ios::exceptions #include <iostream> #include <fstream> #include <string>  int main () {     std::ifstream file;     file.exceptions(ifstream::failbit | ifstream::badbit);     try {         file.open ("test.txt");         std::string buf;         while (std::getline(file, buf))             std::cout << "Read> " << buf << "\n";     }     catch (ifstream::failure& e) {         std::cout << "Exception opening/reading file\n";     } } 
like image 137
kennytm Avatar answered Oct 01 '22 16:10

kennytm