
This is the Title of the Book, eMatter Edition
Copyright © 2007 O’Reilly & Associates, Inc. All rights reserved.
Introduction
|
369
to be thrown. Remember that throwing an exception has a negative impact on per-
formance, whereas exception-handling code has a minimal impact on performance,
as long as an exception is not thrown.
To illustrate this, here is a method that uses exception-handling code to process the
NullReferenceException:
public void SomeMethod( )
{
try
{
Stream s = GetAnyAvailableStream( );
Console.WriteLine("This stream has a length of " + s.Length);
}
catch (Exception e)
{
// Handle a null stream here.
}
}
Here is the method implemented to use an if-else conditional instead:
public void SomeMethod( )
{
Stream s = GetAnyAvailableStream( );
if (s != null)
{
Console.WriteLine("This stream has a length of " + s.Length);
}
else
{
// Handle a null stream here.
}
}
Additionally, you should also make sure that this stream is closed by using the
finally block in the following manner:
public void SomeMethod( )
{
Stream s = null;
try
{
s = GetAnyAvailableStream( );
if (s != null)
{
Console.WriteLine("This stream has a length of " + s.Length);
}
else
{
// Handle a null stream here.
}
}