← Back to Lua Course | Chapter 8: File I/O | Lesson 6 of 7

Handling file errors

A failed io.open returns nil and a message, so check it instead of assuming success.

In this page:

  1. Handling file errors

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

lua
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
Common Mistakes
  1. Ignoring the nil result and calling methods on it
  2. Not closing the file when an error happens midway
  3. 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.