Game Development Reference
In-Depth Information
reader = new StreamReader(string fileName);
ProcessStream(reader);
reader.Close();
}
catch (Exception exception)
{
If (reader != null)
{
reader.Close();
}
throw;
}
}
This solution will ensure that the reader is always closed, but the design of it is
somewhat messy; code is duplicated and it is harder to read.
Structured exception handling in .NET also offers the finally block, which exe-
cutes when the runtime leaves the exception handler, regardless of whether or not
the try or the catch fired.
The following code shows how this would look:
public void DoSomething(string fileName)
{
StreamReader = null;
try
{
reader = new StreamReader(string fileName);
ProcessStream(reader);
}
finally
{
if (reader != null)
{
reader.Close();
}
}
}
To present an even better approach than the finally mechanism, C# has the won-
derful keyword using that implicitly implements the disposable design pattern and
ensures that the resource it is attached to cleans up, even in the event that an
exception occurs. The using keyword only works on classes that implement the
Search Nedrilad ::




Custom Search