How to properly use pcall()?

I’ve only started taking interest in the pcall() function, and I’m confused about how I would use it? I’ve set up a pcall() in a health bar tween function, yet even though I check for the error, the error still gets printed and stops the script. Even if there is a better way for me to handle the tweening and health bar, I’d still like to understand how I should use pcall() as I have other uses for it. I assume I am using it correctly? If not, could someone explain it’s use.

		local succ,err = pcall(function()
				local Bar = newTag.NameHolder.HealthHolder.Bar
				local Humanoid = Char.Humanoid
				if Humanoid.Health >= HealthRanges.Green.Min and Humanoid.Health <= HealthRanges.Green.Max then
					TweenService:Create(Bar,,{BackgroundColor3 = HealthColors.Green}):Play()
				elseif Humanoid.Health >= HealthRanges.Yellow.Min and Humanoid.Health <= HealthRanges.Yellow.Max then
					TweenService:Create(Bar,,{BackgroundColor3 = HealthColors.Yellow}):Play()
				elseif Humanoid.Health >= HealthRanges.Red.Min and Humanoid.Health <= HealthRanges.Red.Max then
					TweenService:Create(Bar,,{BackgroundColor3 = HealthColors.Red}):Play()
		if succ then
			print("Tweened health for; "..Player.Name)
		elseif not succ and err then

Line 5 is where the error happens if the player falls out of the world. This is the error;
'Can only tween objects in the workspace'
Shouldn’t the error be printed at ‘print(err)’?


It would do you well to look up pcall on the Developer Hub or in Lua PiL to establish a fundamental knowledgebase before asking. There is also an existing resource on using pcall.

pcall is protected call. It is intended to call functions and prevent the current thread from terminating upon the function body raising an error. pcall allows you to handle the errors that certain code throws.

In this case, you don’t really need to use a pcall, you just need to fix your code so it doesn’t make assumptions that things are non-nil and properly accounts for cases where something can be nil. pcall shouldn’t be used to skip out on writing proper code, rather to catch and handle errors in cases where errors aren’t deterministic and can be unexpected (e.g. a web call returning an error status code).

Hm, alright. Thank you for the information.

Use pcall when something in your script have a risk to fail due to for example bad network such as Get or Set Async. Because of something of those fails will ruin your white script so if it isn’t network calls you should be fine