Try finally when opening a file
Hi all, the following code:
fn main() raises:
var file: FileHandle
try:
file = open("my_file.txt", "r")
print(file.read())
finally:
file.close() # =>error: use of uninitialized value 'file'
gives an error in the finally clause. Adding except doesn't help.
Why is file not visible in finally? Thanks!
9 Replies
You could fail to open the file within the try block, so you reach finally with an uninitialized ‘file’ variable
That's true. But I tried to initialize the FileHandle with for example: var file: FileHandle = FileHandle("my_file.txt", "r")
Congrats @Ivo Balbaert, you just advanced to level 4!
According to the documentation, this Constructs the FileHandle
the try block is scoped, so the initialization is only happening within this scope, otherwise
file
is still uninialized. you can move the close statement to the try block instead.Thanks. In the try block would it still close the filep properly when an error happened just before that?
file I mean. The finally clause should be made to clean up. Of course it would be perhaps better to use with then.
Also after an exception, the finally block is not executed. This seems like a bug.
the error would be in opening the file and initializing the file handle, in the case there are no resources to free.
Sorry I was wrong, the finally block is executed. Probably Mojo's memory management has already cleared out the file variable when coming in the finally block.
Having not seen the full code, if you assign to the same variable a new value, the old memory location is destroyed ASAP. So the variable starts again with uninitiatialzed state.