a naive question about the exception in fstream

N

Newsgroup - Ann

The fstream is supposed to be a replacement of the stdio.h and the exception
is supposed to be a replacement of the return error code. So how do I
replace my old codes of the style:

if (output = fopen(...) == NULL) {
perror("...");
exit(1);
}

by the C++ style? The only thing I can do now is like

fstream output("...", ios_base::eek:ut);
if (!output.is_open()) {
cerr << "..." << endl;
exit(1);
}

how do I use exception here? Or I should not?

Ann
 
D

Davlet Panech

Newsgroup - Ann said:
The fstream is supposed to be a replacement of the stdio.h and the exception
is supposed to be a replacement of the return error code. So how do I
replace my old codes of the style:

if (output = fopen(...) == NULL) {
perror("...");
exit(1);
}

by the C++ style? The only thing I can do now is like

fstream output("...", ios_base::eek:ut);
if (!output.is_open()) {
cerr << "..." << endl;
exit(1);
}

how do I use exception here? Or I should not?

Ann

Exceptions in streams are disabled by default; you can enable by calling the
"exceptions" member of ios_base (from which all streams are derived). You'll
receive an exception of type "std::ios_base::failure" derived from
"std::exception":

fstream output;

// Throw exceptions whenever "failbit" or "badbit" gets set
output.exceptions (ios::failbit | ios::badbit);

try
{
// Open will throw on error
output.open ("...", ios::eek:ut);
}
catch (exception &x)
{
cerr << "error: " << x.what () << endl;
}

The problem with this method is that you can't really tell what caused an
error, and the message inside the exception object is not very informative
(in most implementations, anyway). Personally, I think the "C-style" error
checking is almost always preferrable with streams, especially considering
that many environments set the errno appropriately:

fstream output ("filename", ios::eek:ut);
if (!output)
{
// print out or throw the description of current errno value (perror,
strerror).
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,767
Messages
2,569,572
Members
45,045
Latest member
DRCM

Latest Threads

Top