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
toasty
toasty3w ago
You could fail to open the file within the try block, so you reach finally with an uninitialized ‘file’ variable
Ivo Balbaert
Ivo BalbaertOP3w ago
That's true. But I tried to initialize the FileHandle with for example: var file: FileHandle = FileHandle("my_file.txt", "r")
ModularBot
ModularBot3w ago
Congrats @Ivo Balbaert, you just advanced to level 4!
Ivo Balbaert
Ivo BalbaertOP3w ago
According to the documentation, this Constructs the FileHandle
Mohamed Mabrouk
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.
Ivo Balbaert
Ivo BalbaertOP3w ago
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.
Mohamed Mabrouk
the error would be in opening the file and initializing the file handle, in the case there are no resources to free.
Ivo Balbaert
Ivo BalbaertOP3w ago
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.
ivellapillil
ivellapillil2w ago
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.

Did you find this page helpful?