3
\$\begingroup\$

I want to keep my game running as much as possible for the user, obviously. They would be dissapointed if the game suddenly quits without leaving any notice behind, and it would be difficult for them to reproduce the error so I can fix it.

So when an exception is thrown, say, an ArrayIndexOutOfBoundsException, how should I handle it?

My current flow goes: DesktopLauncher > MyGame > Menu Screen / Game Screen / other screens

\$\endgroup\$

1 Answer 1

0
\$\begingroup\$

I know I'm extremely late to the party, but since I've encountered a similar roadblock recently, I'll share my own findings, with a hope it will help someone facing a similar issue in the future.

If you want some sort of "global" handling, in order to, for example, display error messages to the user, you can do as I did - but this is by no means a perfect solution.

Let's suppose your MyGame class extends Game or implements ApplicationListener. If that's the case, you can override its create(), render() methods and so on. If you do not use the main class, you can override these methods like so:

@Override
public void render() {
    try {
        super.render();
    } catch (Exception e) {
        handleError(e);
    }
}

You can do the same to other methods, such as create(), pause(), resume(). This ensures that when an exception is thrown somewhere, the MyGame object will be able to intercept it.

Treat my handleError(e) as a placeholder for what you actually want to do. You can use some platform dependent error display - for example, you can use Swing on desktop, but something else for Android.

Also, you might want to ensure everything gets disposed properly when you handle an exception and have the program terminate as a result.

\$\endgroup\$

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.