The C++ std::ios::exceptions() function is used to manage the state flags of input/output stream objects and determine which of these flags will trigger exceptions. By calling this function, a stream can be set to throw exceptions for specific error states such as failbit, badbit or EOF.
This mask is an object of member type iostate, which is a value formed by any combination of the following member constants −
value
(member constants)
indicates functions to check state flags good() eof() fail() bad() rdstate() goodbit No errors (zero value iostate)true
false
false
false
goodbit eofbit End-of-File reached on input operation false
true
false
false
eofbit failbit Logical error on i/o operation false
false
true
false
failbit badbit Read/writing error on i/o operation false
false
true
true
badbit Syntax
Following is the syntax for std::ios::exceptions() function.
iostate exceptions() const; void exceptions (iostate except);Parameters
It returns a bitmask of member type iostate representing the existing exception mask before the call to this member function.
ExceptionsIf an exception is thrown, the stream is in a valid state.
Data racesAccesses or modifies the stream object.
Concurrent access to the same stream object may cause data races.
ExampleIn the following example, we are going to consider the basic usage of the exceptions() function.
#include <iostream> #include <sstream> int main() { std::istringstream a("11 CIAZ"); int x; try { a.exceptions(std::ios::failbit); a >> x; std::cout << "Number read: " << x << std::endl; a >> x; } catch (const std::ios_base::failure& e) { std::cerr << " " << e.what() << std::endl; } return 0; }Output
Output of the above code is as follows −
Number read: 11 basic_ios::clear: iostream errorExample
Consider the following example, where we are going to set the badbit manually to simulates a bad write operation.
#include <iostream> #include <sstream> int main() { std::ostringstream a; a.exceptions(std::ostringstream::badbit); try { a << "TutorialsPoint, TP!"; a.setstate(std::ios_base::badbit); a << "Welcome"; } catch (const std::ios_base::failure& e) { std::cerr << " " << e.what() << '\n'; } return 0; }Output
Following is the output of the above code −
basic_ios::clear: iostream error
ios.htm
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4