How to - Error handling question 
Author Message
 How to - Error handling question

Consider the code segment below.

What I want to do is write a text file to disk. However , if an exception
occurs, for example the file is already in use or whatever, I want to set a
flag which is done in the catch block, but then I want to close the
streamwriter in the finally block. But I get an error "Use of unassigned
local variable 'sw'" . How do I write the following block of code to avoid
this problem but still close the streamwriter in the finally block whether
an error occurs or not.

Thanks

-------------------------------------------------------
StreamWriter sw   ;
   try
   {
    FileInfo FI = new FileInfo(Path.Combine(ApplicationPath ,
GeneratedDataFilename ) ) ;
    sw = FI.CreateText() ;
    sw.Write(fileXmlContent) ;
   }
   catch (Exception e)
   {
    success = false  ;
   }
   finally
   {
    sw.Close() ;
   }
------------------------------------------------------------



Mon, 28 Mar 2005 17:34:08 GMT  
 How to - Error handling question
Write:
StreamWriter sw = null;
...

Jos

Quote:
> Consider the code segment below.

> What I want to do is write a text file to disk. However , if an exception
> occurs, for example the file is already in use or whatever, I want to set
a
> flag which is done in the catch block, but then I want to close the
> streamwriter in the finally block. But I get an error "Use of unassigned
> local variable 'sw'" . How do I write the following block of code to avoid
> this problem but still close the streamwriter in the finally block whether
> an error occurs or not.

> Thanks

> -------------------------------------------------------
> StreamWriter sw   ;
>    try
>    {
>     FileInfo FI = new FileInfo(Path.Combine(ApplicationPath ,
> GeneratedDataFilename ) ) ;
>     sw = FI.CreateText() ;
>     sw.Write(fileXmlContent) ;
>    }
>    catch (Exception e)
>    {
>     success = false  ;
>    }
>    finally
>    {
>     sw.Close() ;
>    }
> ------------------------------------------------------------



Mon, 28 Mar 2005 19:03:39 GMT  
 
 [ 2 post ] 

 Relevant Pages 

1. newbie CWinThread error handling question

2. ADO error handling question

3. Question On Error Handling in C#

4. newbie question: 'handling' handle/callback

5. Error handling / Error recovery.

6. error handling and exit of ServiceBase-derived app

7. Is there a way to turn off error handling in C#

8. Error Handling

9. Error Handling in ATL Server in SRF files

10. C# and error handling

11. goto for error handling

12. Error Handling

 

 
Powered by phpBB® Forum Software