J
JSheble
I'm writing some code that interacts with MSMQ, and am getting in the habit
of using try{}catch{}finally{} blocks, but am now running into a problem
with un-initialized variables... for example, consider the following method:
private void GetQMessage()
{
System.Messaging.Message oMsg;
System.Messaging.MessageQueue oMsgQ = new MessageQueue(this.StatusQ);
oMsgQ.Formatter = new XmlMessageFormatter(new Type[] {typeof(String)});
try
{
oMsg = oMsgQ.Receive(new TimeSpan(0, 0, 0, 15, 0));
if(((String) oMsg.Body) != "")
{
this.lstActivity.Items.Insert(0, (String) oMsg.Body);
}
else
{
this.lstActivity.Items.Insert(0, "QWatcher Appears To Be Idle");
}
}
catch(MessageQueueException err)
{
if(err.MessageQueueErrorCode == MessageQueueErrorCode.IOTimeout)
{
this.lstActivity.Items.Insert(0, "QWatcher Appears To Be Idle");
}
}
finally
{
if(this.lstActivity.Items.Count > 250)
{
this.lstActivity.Items.RemoveAt(250);
}
oMsg.Dispose();
oMsgQ.Dispose();
}
}
When I compile this, I get the following error: FormMain.cs(129): Use of
unassigned local variable 'oMsg', which points to the oMsg.Dispose() call in
the finally block.
Now I like the fact that each block of code can have it's own variable
scope, but when using exception handling, it's a bit inconvienent. SO
what's the best way of handling this?? SHould I always initialize the
actual object to an empty object? (i.e. Message oMsg = new Message()
of using try{}catch{}finally{} blocks, but am now running into a problem
with un-initialized variables... for example, consider the following method:
private void GetQMessage()
{
System.Messaging.Message oMsg;
System.Messaging.MessageQueue oMsgQ = new MessageQueue(this.StatusQ);
oMsgQ.Formatter = new XmlMessageFormatter(new Type[] {typeof(String)});
try
{
oMsg = oMsgQ.Receive(new TimeSpan(0, 0, 0, 15, 0));
if(((String) oMsg.Body) != "")
{
this.lstActivity.Items.Insert(0, (String) oMsg.Body);
}
else
{
this.lstActivity.Items.Insert(0, "QWatcher Appears To Be Idle");
}
}
catch(MessageQueueException err)
{
if(err.MessageQueueErrorCode == MessageQueueErrorCode.IOTimeout)
{
this.lstActivity.Items.Insert(0, "QWatcher Appears To Be Idle");
}
}
finally
{
if(this.lstActivity.Items.Count > 250)
{
this.lstActivity.Items.RemoveAt(250);
}
oMsg.Dispose();
oMsgQ.Dispose();
}
}
When I compile this, I get the following error: FormMain.cs(129): Use of
unassigned local variable 'oMsg', which points to the oMsg.Dispose() call in
the finally block.
Now I like the fact that each block of code can have it's own variable
scope, but when using exception handling, it's a bit inconvienent. SO
what's the best way of handling this?? SHould I always initialize the
actual object to an empty object? (i.e. Message oMsg = new Message()
