try...catch and XS0165 (Use of unassigned local variable...)

This forum is meant for questions and discussions about the X# language and tools
Post Reply
kitz
Posts: 87
Joined: Wed Nov 29, 2017 8:56 am

try...catch and XS0165 (Use of unassigned local variable...)

Post by kitz »

Hi!
This:
LOCAL oSR as StreamReader
TRY
oSR := StreamReader(cFile)
do while....
enddo
CATCH ex...
FINALLY
oSR:Close()
END TRY
creates error XS0165 for variable oSR.
My question is, how to handle this.
Is oSR already created before exceptions arise? The I consider it OK to do it like that and the message is wrong.
If oSR is NOT already created before exceptions occur, then must I use a separate TRY around the creation of oSR?
User avatar
Chris
Posts: 4562
Joined: Thu Oct 08, 2015 7:48 am
Location: Greece

try...catch and XS0165 (Use of unassigned local variable...)

Post by Chris »

It is possible that the constructor of StreamReader fails and throws in exception, in which case oSR will never be assigned indeed, I think that's the theory behind this. In order to get rid of it, you could just assign the var to NULL before the TRY construct, although this is a bit like cheating :)

Alternatively, you could use a BEGUN USING instead, which also takes care of the closing/disposing of the object:

Code: Select all

BEGIN USING VAR oSR := StreamReader{"..."}
	...
END USING
Chris
Chris Pyrgas

XSharp Development Team test
chris(at)xsharp.eu
kitz
Posts: 87
Joined: Wed Nov 29, 2017 8:56 am

try...catch and XS0165 (Use of unassigned local variable...)

Post by kitz »

Thanks, Chris!

I found another solution:
TRY
oSR := StreamReader(cFile)
try
do while...
enddo
catch...
finally
oSR:Close()
end try
CATCH...
END TRY (note: no FINALLY here, or at least no oSR:Close in it)

BR Kurt
Post Reply