Variable scope bug?

  • Thread starter Thread starter Andrew Todd
  • Start date Start date
A

Andrew Todd

I've got a problem with the scope of a variable, consider
the following example:


MyCOMObject.MyObjectClass obj;

try
{
obj = new MyCOMObject.MyObjectClass();
returnXml = obj.getEnquiryUsers();
}
catch (Exception e)
{
//handle error
}
finally
{
if (obj!=null)
{
Marshal.ReleaseComObject(obj);
obj = null;
}
}

This won't compile, it tells me that the variable obj is
unassigned when I test if it's null in the finally
statement.

This doesn't seem correct to me; I need to release the
COM object in the finally statement as if there is an
error in the try block the object will never be released.
These steps work in Java and are the steps we normally
take when interfacing with COM objects, is this a bug?

Thanks
Andrew
 
If the statement "new MyCOMObject.MyObjectClass()" were to throw an
exception then obj would not have been assigned, and thus the warning in the
finally clause.

You need to decide whether exceptions resulting from creating the object
need to be handled here (in which case set obj to null beforehand), or
whether you aren't handling them here (in which case create the object
outside the try block).

HTH,

Stu
 
Andrew Todd said:
I've got a problem with the scope of a variable, consider
the following example:

This won't compile, it tells me that the variable obj is
unassigned when I test if it's null in the finally
statement.

Indeed, and it's right. Set it to null to start with. Local variables
don't have any default value; they need to be definitely assigned
before they're read.
This doesn't seem correct to me; I need to release the
COM object in the finally statement as if there is an
error in the try block the object will never be released.
These steps work in Java and are the steps we normally
take when interfacing with COM objects, is this a bug?

No, it wouldn't work in Java. Here's an example showing it:

public class Test
{
public static void main(String[] args)
{
String x;
try
{
x = "hello";
}
catch (Exception e)
{
System.out.println (e);
}
finally
{
if (x==null)
{
System.out.println ("Oops");
}
}
}
}

And compiling it:

Test.java:16: variable x might not have been initialized
if (x==null)
^
1 error
 
Back
Top