Last active
August 29, 2015 13:57
-
-
Save ebot/9418228 to your computer and use it in GitHub Desktop.
Fun with java threads, exceptions, and exception handlers
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class SimpleThread extends Thread { | |
private int countDown = 5; | |
private boolean triggerExceptions = false; | |
public SimpleThread( boolean enableHandler, boolean triggerExceptions) { | |
super("Error Test"); // Store the thread name | |
this.triggerExceptions = triggerExceptions; | |
if (enableHandler) setHandler(); | |
start(); | |
} | |
public String toString() { | |
return " #" + getName() + ": " + countDown + " (Stopping at 0)"; | |
} | |
public void run() { | |
while(true) { | |
try { | |
System.out.println(this); | |
if (countDown == 3 && triggerExceptions) exception(); | |
if (countDown == 2 && triggerExceptions) internalError(); | |
} | |
catch (Exception e ) { | |
System.err.println(" ERROR CAUGHT: " + e.getMessage()); | |
} | |
finally { | |
if(--countDown == 0) return; // MAX of 5 loops | |
try { | |
Thread.sleep( 1000 ); | |
} | |
catch (InterruptedException Ex) { | |
/* do nothing */ | |
} | |
} | |
} | |
} | |
private void setHandler() { | |
this.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() { | |
public void uncaughtException(Thread t, Throwable e) { | |
System.err.println(t + " I resurrected from death: " + e); | |
} | |
}); | |
} | |
private void internalError() { | |
throw new InternalError("This is very bad and it will kill you, Die Motherfucker!"); | |
} | |
private void exception() { | |
throw new RuntimeException("This is bad, but it will not kill you :-)"); | |
} | |
public static void main(String[] args) { | |
//System.out.println("Running with no errors:"); | |
//new SimpleThread(false, false); | |
//System.out.println("Running errors and a try catch:"); | |
//new SimpleThread(false, true); | |
System.out.println("Running with errors and an excption handler:"); | |
new SimpleThread(true, true); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment