Lua - Error handling in File Operations



During File I/O, error can come in any variety like a file is not available, or file is not accessible or not writeable during write operations and so on. Now in order to handle such errors during file operations, we can use pcall() (protected call) function.

Syntax - pcall() method

result, error = pcall(functionIO)

Where functionIO represents the function doing the I/O operation.

  • result− result is true if there is no error reported by function called within pcall() method otherwise false is returned.

  • error− nil in case of no error otherwise, it contains the error details.

We can check if a file exists or not using io.exists() method as well and throw error if file is not present before moving ahead.

if not io.exists() then
   error("File is not present")
end

Example - Handling error using pcall() while reading a file

Let us now see how to handle error while reading a file.

main.lua

-- read a file content and returns the same
function readFile(filename)
   local result, err = pcall(function()
         -- Opens a file in read
         f = io.open(filename,"r")
         -- read all lines
         contents = f:read("*all")
         print(contents)
         -- close the file handle
         f:close()
      end
   )

   if not result then
      print("Error reading file:", err)
   end
   return result
end

-- read existing file
result = readFile("example.txt")
print("Result", result)

-- try to read non-existing File
result = readFile("example1.txt")
print("Result", result)

Output

When the above code is built and executed, it produces the following result −

Welcome to tutorialspoint.com
Simply Easy Learning

Result	true
Error reading file:	main.lua:8: attempt to index global 'f' (a nil value)
Result	false

Example - Throwing a custom message while reading a file

Let us now add another check for existing file check along with pcall() while reading a file and throwing a custom message to the user.

main.lua

-- read a file content and returns the same
function readFile(filename)
   local result, err = pcall(function()
         -- Opens a file in read
         f = io.open(filename,"r")

         if f then
            -- read all lines
            contents = f:read("*all")
            print(contents)
            -- close the file handle
            f:close()
         else
            error ("File is not present")
         end
      end
   )

   if not result then
      print("Error reading file:", err)
   end
   return result
end

-- read existing file
result = readFile("example.txt")
print("Result", result)

-- try to read non-existing File
result = readFile("example1.txt")
print("Result", result)

Output

When the above code is built and executed, it produces the following result −

Welcome to tutorialspoint.com
Simply Easy Learning

Result	true
Error reading file:	main.lua:19: File is not present
Result	false
Advertisements