To improve performance, you should programmatically handle the case when an exception could be thrown versus catching the exception after it is thrown. For example, if a method has a good chance of returning a null value, you could test the returned value for null before that value is used, as opposed to using a try-catch block and allowing the NullReferenceException to be thrown. Remember that throwing an exception has a negative impact on performance and exception-handling code has no noticeable impact on performance, as long as an exception is not thrown. To illustrate this, we take a method that uses exception handling code to handle 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. } }
and convert this method to use an if-else conditional to handle the NullReferenceException as:
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 was 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. } } finally { s.Close( ); } }
The finally block contains the method call that will close the stream, ensuring that there is no data loss.
Popularity: 2% [?]
RSS feed for comments on this post · TrackBack URI
Leave a reply