How To Initialize Object Which May Be Used In Catch Clause?
Posted
by
Onorio Catenacci
on Programmers
See other posts from Programmers
or by Onorio Catenacci
Published on 2012-10-17T19:50:39Z
Indexed on
2012/10/17
23:19 UTC
Read the original article
Hit count: 297
memory
|exception-handling
I've seen this sort of pattern in code before:
//pseudo C# code
var exInfo = null; //Line A
try
{
var p = SomeProperty; //Line B
exInfo = new ExceptionMessage("The property was " + p); //Line C
}
catch(Exception ex)
{
exInfo.SomeOtherProperty = SomeOtherValue; //Line D
}
Usually the code is structured in this fashion because exInfo has to be visible outside of the try clause. The problem is that if an exception occurs on Line B, then exInfo will be null at Line D. The issue arises when something happens on Line B that must occur before exInfo is constructed. But if I set exInfo to a new Object at line A then memory may get leaked at Line C (due to "new"-ing the object there). Is there a better pattern for handling this sort of code? Is there a name for this sort of initialization pattern?
By the way I know I could check for exInfo == null before line D but that seems a bit clumsy and I'm looking for a better approach.
© Programmers or respective owner