
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() ;
}
------------------------------------------------------------