Python has try: except: , but what does ROBLOX lua have it?

The most obvious answer will be if and else, but here is a common problem I keep finding in my code:

So I use if and else a lot, and (in my opinion) it makes code really really messy.
(It gets messy when you constantly have to check and check that instances exist, else they can’t be referenced and will therefore result in an error.)

I recently made a mini round-based game (as it has been years since I have done one), and a common problem was this:

If a player leaves whilst the program is running (matchmaking system), then the PlayerGui is removed. So when the system wants to change the player’s gui, it can’t.
This results in an error, and the whole script stops running, which breaks the game.

if and else do help this problem of course, but it will never be able to fix it.

Right now, I’m looking for different ways to do this, but nothing has yet come to mind.

The real question is, does roblox have this kind of code available?
It would really help me (and other unaware developers) fix this common problem;

However, if roblox doesn’t have something like this, then they should certainly add it.

2 Likes

I am aware that there is a Promise implementation by @evaera which you can find here. Roblox doesn’t naturally have this implementation so you would be looking at libraries and implementations developed by other people.

There’s also an older library from @GigsD4X that has the try/catch aspect you’re looking for which you can find here.

5 Likes

You could use pcall, which is the exception handler for Lua. However, you should only use try catch in python/pcall in Lua when the exception is out of your control (i.e. the function you call makes a web request). Instead of putting a bandaid over your script breaking, why not fix the problem itself. I have made round-based games many times and I can help you out with that. You are likely keeping the player in a table or somehow still maintaining a reference to it. This alone brings another issue; memory leaks.

5 Likes

It’s not just the round based game - that was just an example where this problem is common.

I’ll be sure to check these out, thank you!

1 Like