By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
448,676 Members | 1,352 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 448,676 IT Pros & Developers. It's quick & easy.

a naive question about the exception in fstream

P: n/a
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::out);
if (!output.is_open()) {
cerr << "..." << endl;
exit(1);
}

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

Ann
Jul 19 '05 #1
Share this Question
Share on Google+
1 Reply


P: n/a

"Newsgroup - Ann" <ne******@yahoo.com> wrote in message
news:3f********@rcfnews.cs.umass.edu...
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::out);
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::out);
}
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::out);
if (!output)
{
// print out or throw the description of current errno value (perror,
strerror).
}


Jul 19 '05 #2

This discussion thread is closed

Replies have been disabled for this discussion.