: eval 'exec perl -w -S `echo $0 | sed "s/.*\///" ` ${1+"$@"}' if 0; @a=@ARGV; @flags=grep(/^-/,@a); @other=(); @other=grep(!/^-/,@a); if ( grep( /^-h(elp)?$/,@flags) || scalar(@other) != 1) { $scriptName = $0; $scriptName =~ s%^.*/%%; print <<"END"; Usage: $scriptName [-h -help] Class Print out a prototype of a new java class that contains a main() catching all overlooked exceptions END exit;} $Class=$a[0]; print <<"END"; public class $Class { /** Code executed when main is called \@param argv All arguments passed to the command line. */ private static void mainRun(String[] argv) { // Put stuff here that would ordinarily go into main System.out.println("Testing $Class"); System.out.flush(); // Example of exception in another thread. (new Thread() {public void run() {throw new RuntimeException("XXX");}}) .start(); // Create array out of bounds runtime exception int[] small = new int[0]; small[777] = 777; } /** This main calls mainRun and handles all fatal errors. \@throws Throwable Any fatal errors are thrown to ensure non-zero exit code, and to ensure threads have a chance to exit. */ public static void main(final String[] argv) throws Throwable { // You should not need to modify this routine final MainThreadGroup threadGroup = new MainThreadGroup(); final Throwable[] throwable = new Throwable[1]; Runnable starter = new Runnable() {public void run() { try { $Class.mainRun(argv); return; // Successful return } catch (Throwable e) { // Any explicit errors here e.printStackTrace(); throwable[0] = e; } // Stop other threads after an error. threadGroup.interrupt(); }}; Thread thread = new Thread(threadGroup, starter, "${Class} mainRun"); thread.start(); thread.join(); if (throwable[0] != null) throw throwable[0]; threadGroup.throwUncaught(); } /** This ThreadGroup manages the Thread that runs ${Class}.mainRun() */ private static class MainThreadGroup extends ThreadGroup { private volatile Throwable _ex; /* Catches all overlooked RuntimeExceptions here */ \@Override public void uncaughtException(Thread t, Throwable ex) { _ex = ex; try { System.err.println("Overlooked Exception caught by "+ "${Class}.MainThreadGroup: "+ ex.getLocalizedMessage()); ex.printStackTrace(); System.err.flush(); } finally { interrupt(); } } private void throwUncaught() throws Throwable { if (_ex != null) throw _ex; } public MainThreadGroup() {super ("${Class}.MainThreadGroup");} } } END