Re: Error with ifstream and exceptions
On Feb 8, 1:26 am, "Alf P. Steinbach /Usenet" <alf.p.steinbach
+use...@gmail.com> wrote:
* James Kanze, on 08.02.2011 02:03:
Where did you read that? Using an exception to report an
inexistant file is very bad software engineering, and should
only be done if you have no other choice. Which isn't the case
in C++.
That's a very subjective opinion.
It depends. Not having the choice, and always using an
exception, is very bad software engineering. In the case of the
OP's code, it's also very bad software engineering. At the
other extreme, if you're opening some sort of configuration
file, installed with your executable, or a file with data you've
written earlier, then an exception is certainly appropriate
(unless you actually exit). In between, it's a gray area; you
wouldn't normally use exceptions when opening a file whose name
was user input, but I imagine that there are exceptions even
there.
When done properly, it can yield more clear and maintainable code.
I think possibly you're assuming a false dichotomy, that it's
either exception or possibility of checking result of open
attempt.
As with any error, its a tricotomy: you can abort, you can raise
an exception, or you can return an error code. (Actually, in
the case of input, you can also just continue; there are cases
where the correct handling of a missing file is to treat it as
if it were empty.)
With that as (incorrect) assumption you'd have to choose the
practically least evil.
But it isn't either/or, and it isn't necessary to force client
code to do needless check or force it to needlessly deal with
an exception.
Agreed. I was speaking very much in the context of the OP's
code. But such cases do seem to be the majority, at least in
beginning programmers' code.
--
James Kanze