CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 3 of 3
  1. #1
    Join Date
    Feb 2008
    Posts
    56

    Output stream not closed

    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:

    Code:
    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!

  2. #2
    Join Date
    Oct 2000
    Location
    London, England
    Posts
    4,773

    Re: Output stream not closed

    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:
    Code:
    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).

  3. #3
    Join Date
    Feb 2008
    Posts
    56

    Re: Output stream not closed

    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!

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured