Hi,
I've updated my local copy of StandardGame to improve it's uncaught exception handling.
Basically I've created a new method that allows a UncaughtExceptionHandler to be added to the gameThread and created a new default handler. The default handler just prints out to the logger and ends the game, which if I'm not mistaken is the same behaviour as the current try/catch block. The obvious improvement comes if users code their own handlers which among other things could restart the game loop, open error reporting tools etc etc.
Here is a diff patch I exported using netBeans. I'm not sure how diff patches are meant to look so if this is completely useless let me know and I'll just paste all the changed methods
# It uses platform neutral UTF-8 encoding and n newlines.
# Above lines and this line are ignored by the patching process.
Index: StandardGame.java
*** srccomjmexgameStandardGame.java Base (1.2)
--- srccomjmexgameStandardGame.java Locally Modified (Based On 1.2)
***************
*** 31,36 ****
--- 31,37 ----
*/
package com.jmex.game;
+ import java.lang.Thread.UncaughtExceptionHandler;
import java.util.concurrent.*;
import java.util.logging.Level;
import java.util.prefs.Preferences;
***************
*** 110,116 ****
}
public void start() {
! gameThread = new Thread(this);
gameThread.start();
// Wait for main game loop before returning
--- 111,119 ----
}
public void start() {
! if (gameThread == null) {
! setUncaughtExceptionHandler(new DefaultUncaughtExceptionHandler());
! }
gameThread.start();
// Wait for main game loop before returning
***************
*** 144,150 ****
}
// Main game loop
- try {
float tpf;
started = true;
while ((!finished) && (!display.isClosing())) {
--- 147,152 ----
***************
*** 181,190 ****
Thread.yield();
}
started = false;
- } catch(Throwable t) {
- LoggingSystem.getLogger().log(Level.SEVERE, "Main game loop broken by uncaught exception", t);
- }
cleanup();
quit();
}
--- 183,193 ----
Thread.yield();
}
+
started = false;
cleanup();
quit();
***************
*** 431,437 ****
--- 431,468 ----
public boolean isStarted() {
return started;
}
+
+ /**
+ * Sets the uncaught exception handler on the main game thread.
+ *
+ * @param eh The uncaught exception handler.
+ */
+ public void setUncaughtExceptionHandler(UncaughtExceptionHandler eh) {
+ if (gameThread == null) {
+ gameThread = new Thread(this);
}
+
+ gameThread.setUncaughtExceptionHandler(eh);
+ }
+
+
+
+
+
+ private class DefaultUncaughtExceptionHandler implements UncaughtExceptionHandler {
+ public void uncaughtException(Thread t, Throwable e) {
+ if (t == gameThread) {
+ LoggingSystem.getLogger().log(
+ Level.SEVERE, "Main game loop broken by uncaught exception", e);
+
+ cleanup();
+ quit();
+ }
+ }
+ }
+
+ }
Anyhoo let me know what you think :)
- Chris