Heartbeat vs While loop in Error Handling

Can someone explain the difference in error handling between a heartbeat event and a while loop? I found that heartbeat continues to run even if it encounters an error, while a while loop breaks. This might be the answer, but I want to know is there a specific term for functions that handle errors directly? Like how come a heartbeat can handle errors directly but a while loop can’t? Because heartbeat needs to rely on its consistency?

1 Like

heartbeat continues to run after errors, because it’s just a callback being called repeatedly. same as a .touched event. even if you use .touched and the code using it throws an error, .touched will still be detecting objects touching right? because it doesn’t break even if your script errors. and while? you can guess

Errors that happen in a function stop that function from running any further, which is what you see in the while loop.

while true do
    print("this prints")
    local value = 5 + true -- This line errors, terminating the loop
    print("this doesn't print")
    task.wait()
end

Functions that are connected to events can still error (and will halt execution when doing so), but since they remain connected to that event they will still be called.

local function error_function()
    return error('Error function was called!')
end

local connection = game:GetService('RunService').Heartbeat:Connect(function() 
    error_function()
    
    -- Since error_function caused the function to error and stop running,
    -- every line below will never run
    print("this doesn't print") 
end)

task.wait(5)

connection:Disconnect()

In this case, error_function will be called every frame until the connection:Disconnect() line is ran.

If you want to research more about error handling try looking into functions like pcall, which lets you “catch” errors without the function terminating. Note that it’s generally a better idea to prevent errors in the first place when you can, rather than constantly deal with them!

2 Likes

so events are basically wrappers for functions that when fired the connects the function each time regardless of its content? events just work this way so the result of a function cant stop the execution of the event? am i getting the logic corrent on events and still dont understand why a while loop would break if it catches an error why cant it just continue to the next iteration?