File Errors को Handle करना
एक failed io.open nil और एक message return करता है, इसलिए success मान लेने की बजाय इसे check करें।
In this page:
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
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
आम गलतियां
- nil result ignore करना और इस पर methods call करना
- बीच में एक error होने पर file close न करना
- यह उम्मीद करना कि 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: