Click to See Complete Forum and Search --> : Output stream not closed


Luc484
February 10th, 2008, 11:29 AM
Hi! I'm trying to write to a file stream, so I open a file I want to write to and I catch the exception I throw in case of problems. Inside the same try block, I throw another exception in same cases, using a different value for the parameter. In that case, I want to write something into the same exact file I opened before. Unfortunately, the variable of type ofstream already declared cannot be used as it is declared in a different block. So I created another variable of type ofstream for the same output file. Is this correct? Can I do this? I mean, can I do this even if the stream of the try block was not closed correctly (the exception is thrown before the stream can be closed)? This is an example:

try
{
ofstream streamOut("output");
if (!streamOut) throw(0);
// do something
... throw(1);
// do something else
streamOut.close();
}
catch(int error)
{
if (error == 0) // do something
else if (error == 1)
{
ofstream streamOut("output");
//write something
streamOut.close();
return 1;
}
}
return 0;

Is this permitted?
Thanks!

NMTop40
February 10th, 2008, 11:50 AM
The stream will close automatically when it leaves the try block so yes you would have to reopen it, but it will overwrite any existing contents unless you open the file to append.

It is not normal to throw ints, but it is legal. However try..throw..catch like that within the same function is not recommended. throw is useful when you have an error to report but want to pass it back to the caller to handle. When you are planning to handle the error yourself it is best to just use boolean logic.

You might want an external function if you are likely to call it from many places:

int handle_error( std::ostream &, const std::string & errorDesc )
{
// do whatever
return 1;
}


then in your code if an error occurs call return handle_error() passing in the relevant parameters, which will also get your function to immediately return 1. (You could make the return value a parameter too if you want).

Luc484
February 10th, 2008, 07:01 PM
Thank you very much. Actually the throws are thrown from within other functions. That was only an example to explain the what I was saying. The throws are not all inside the try block.
Thanks again!