← Back to Lua Course | Chapter 5: Functions | Lesson 7 of 7

pcall से Error Handling

pcall code safely चलाता है और program crash करने की बजाय आपको error देता है।

pcall से Error Handling

function error(msg) एक error raise करता है और assert(cond, msg) एक raise करता है जब cond falsy हो। pcall(f, ...) protected mode में f call करता है और true plus results, या false plus error value return करता है। Errors tables समेत कोई भी value हो सकते हैं, और एक string वाला error position add करता है जब तक आप level 0 pass न करें।

Note: जब आपको एक stack trace चाहिए तो handler की तरह debug.traceback के साथ xpcall इस्तेमाल करें।

उदाहरण: Error handling with pcall

lua
print(pcall(function() return "fine", 2 end))
local ok, err = pcall(function() error("boom", 0) end)
print(ok, err)
local ok3, e3 = pcall(error, {code = 42})
print(ok3, e3.code)
local ok2, e2 = pcall(function() local x = nil; return x.field end)
print(ok2, type(e2))
print(pcall(assert, false, "assertion msg"))
print(select(2, pcall(assert, 1 == 1, "unused")))

-- Output:
-- true	fine	2
-- false	boom
-- false	42
-- false	string
-- false	assertion msg
-- true	unused
{# 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. यह भूल जाना कि pcall पहले true या false return करता है
  2. status ignore करना और error को एक result की तरह इस्तेमाल करना
  3. यह उम्मीद करना कि error messages में कभी file और line information नहीं होगी
चैप्टर सारांश
  • error एक error raise करता है
  • assert एक condition check करता है
  • pcall एक status फिर results return करता है
  • Errors कोई भी value हो सकते हैं

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.