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

File Errors को Handle करना

एक failed io.open nil और एक message return करता है, इसलिए success मान लेने की बजाय इसे check करें।

File Errors Handle करना

जब io.open fail हो यह nil, एक error message, और एक numeric error code return करता है। आप result को एक if से test कर सकते हैं, failure को एक error में बदलने के लिए assert इस्तेमाल कर सकते हैं, या message text check कर सकते हैं। File work को pcall में wrap करना सुनिश्चित करता है कि एक failure close होने को skip न करे।

Note: उन scripts के लिए जहाँ failure को program रोकना चाहिए assert(io.open(...)) में io.open wrap करें।

उदाहरण: 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/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. nil result ignore करना और इस पर methods call करना
  2. बीच में एक error होने पर file close न करना
  3. यह उम्मीद करना कि io.open खुद एक error raise करेगा
चैप्टर सारांश
  • io.open failure पर nil, message, code return करता है
  • assert failure को एक error में बदलता है
  • handle इस्तेमाल करने से पहले check करें
  • pcall file work protect करता है
🔒

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.