Handling file errors
A failed io.open returns nil and a message, so check it instead of assuming success.
In this page:
Handling file errors
When io.open fails it returns nil, an error message and a numeric error code. You can test the result with an if, use assert to turn the failure into an error, or check the message text. Wrapping file work in pcall makes sure a failure does not skip closing.
Note:
Wrap io.open in assert(io.open(...)) for scripts where failure should stop the program.
Example: Handling file errors
local f, err, code = io.open("/tmp/no_such_dir_xyz/file.txt", "r")
print(f, err, code)
local ok, e = pcall(function()
local h = assert(io.open("/tmp/no_such_dir_xyz/file.txt"))
h:close()
end)
print(ok, e:match("No such file or directory"))
-- Output:
-- nil /tmp/no_such_dir_xyz/file.txt: No such file or directory 2
-- false No such file or directory
Login to try C/C++/Java/PHP code in the editor
Common Mistakes
- Ignoring the nil result and calling methods on it
- Not closing the file when an error happens midway
- Expecting io.open to raise an error itself
Chapter Summary
- io.open returns nil, message, code on failure
- assert converts failure into an error
- Check before using the handle
- pcall protects file work
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: