4 posts
Posted 22 December 2014 - 10:59 PM
Hello, recently I have found the need to detect if a certain piece of code will crash the program and therefore produce a error. I am familiar with other programming languages such as python which has try and except. These pieces of code detect if the code will cause a crash and if it does it runs the code in the except section.
Is there a way to replicate this in ComputerCraft? It would be incredibly useful.
Thank you.
7508 posts
Location
Australia
Posted 22 December 2014 - 11:11 PM
Lua has the function
pcall (
PiL link) to catch errors, usage example
--[[
ok will be a boolean of running success
msg will either be the error message (if it failed) or the first return result from the function (if it succeeded).
we give it the function pointer, and any arguments it needs to be invoked with
--]]
local ok, msg = pcall(term.setCursorPos, 1, 1)
if not ok then
print( msg ) --# print the reason it failed
end
since this can only do one instruction at a time I prefer to use the following model
local function main( tArgs )
--# run program here, any uncaught errors will be caught by the main pcall below
end
local ok, err = pcall( main, { ... } )
if not ok and err:lower ~= "terminated" then --# if it failed, and wasn't a termination
print( "The program had fatal error" )
print( err )
end
Edited on 22 December 2014 - 10:11 PM