#functions not capable of returning errors

1 messages · Page 1 of 1 (latest)

upper crescent
#

I've noticed there are some functions, like fs.Dir.close, which do not return an error, but are capable of hitting unreachable code. The comments above the posix.close function state that they are incapable of returning an error (is this a technical limitation?)

What is the user expected to do here? Does unreachable always indicate a mistake from the calling code side? In my case I am purposely calling close on a dir while iterating it in order to better understand error handling in Zig. My expectation was that I'd get back an error which my catch statement would handle.

Am I misunderstanding the contract between the API and failure conditions?
Thanks

low bough
#

unreachable should indicate a mistake from the calling side. closing a dir twice won't give you an error because it can't be detected consistently - so make sure you don't do it

imagine:

const f1 = openFile("some file"); // -> fd 5
f1.close();
const f2 = openFile("some other file"); // -> fd 5
f1.close(); // <- this can't give an error because the fd it holds got reused. so it will close file 2.

closing a file that has already been closed is unreachable because it can't be detected in all cases but you're not allowed to do it

uncut viper
#

theres also a more general rule that resource deallocation must succeed. and if close could return an error you wouldnt be able to use defer on it (easily)

upper crescent
#

I can appreciate the rule about deallocation and how it would make defer harder to use. Though in this case the code would just silently fail (assuming we're running unsafe). Surely there's a case where close() returns EBADF that is not user error, but a real runtime error in the system - in this case wouldn't we want to know that the operation failed?

low bough
#

in ReleaseSafe or Debug, it will panic. EBADF occurs because your code is wrong (calling close() twice). It's different than a runtime error like FileNotFound because that is something that can happen regardless of your code.

upper crescent
#

ok interesting - I guess the argument here is that it is entirely a user error 100% of the time. I.e it can't actually fail due to outside circumstances. I see that EINTR for example is considered a success and there's a debate about it being ok

low bough
#

yeah. if the kernel could randomly close your file descriptors or some other running process could close them, then it's wouldn't be okay for it to be unreachable.