Example usage for java.lang Thread.UncaughtExceptionHandler Thread.UncaughtExceptionHandler

List of usage examples for java.lang Thread.UncaughtExceptionHandler Thread.UncaughtExceptionHandler

Introduction

In this page you can find the example usage for java.lang Thread.UncaughtExceptionHandler Thread.UncaughtExceptionHandler.

Prototype

Thread.UncaughtExceptionHandler

Source Link

Usage

From source file:MainClass.java

public MainClass() {
    Container cp = getContentPane();
    JButton crasher = new JButton("Crash");
    cp.add(crasher);/*from w ww  .  j ava  2 s  . c o m*/
    crasher.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            throw new RuntimeException("You asked for it");
        }
    });
    Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
        public void uncaughtException(Thread t, Throwable ex) {
            System.out.println("You crashed thread " + t.getName());
            System.out.println("Exception was: " + ex.toString());
        }
    });
    pack();
}

From source file:com.mbrlabs.mundus.editor.utils.Log.java

public static void init() {
    System.setErr(new ErrorStreamInterceptor(System.err));
    Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
        @Override/* w w w . java2 s  .c  o m*/
        public void uncaughtException(Thread thread, Throwable throwable) {
            Log.exception(TAG, throwable);
            Log.fatal(TAG, "Uncaught exception occurred, error report will be saved");
            logFileWriter.flush();
        }
    });

    prepareLogFile();
}

From source file:com.compomics.cell_coord.gui.controller.CellCoordController.java

/**
 * Initialize main controller.//from   ww w  .  j av  a  2  s .c  o  m
 */
public void init() {
    //set uncaught exception handler
    Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
        @Override
        public void uncaughtException(Thread t, Throwable e) {
            LOG.error(e.getMessage(), e);
            showMessage("Unexpected error: " + e.getMessage() + ", application will exit", "unexpected error",
                    JOptionPane.ERROR_MESSAGE);
            // exit the application
            System.exit(1);
        }
    });

    // new frame instance
    cellCoordFrame = new CellCoordFrame();
    cellCoordFrame.setVisible(true);
    // at starter, show main panel with logo    
    getCardLayout().first(cellCoordFrame.getTopPanel());
    onCardSwitch();
    // init child controllers
    loadTracksController.init();
    initMainFrame();
}

From source file:fusejext2.JextThreadFactory.java

@Override
public synchronized Thread newThread(Runnable r) {
    final String name = new StringBuilder().append(threadPrefix).append("[").append(count.getAndIncrement())
            .append("]").toString();

    Thread t = new Thread(r);

    t.setName(name);// w ww . ja  v  a2 s. c om

    t.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
        @Override
        public void uncaughtException(Thread t, Throwable e) {
            logger.severe(new StringBuffer().append("Uncaught Exception in thread ").append(name).append("\n")
                    .append(ExceptionUtils.getMessage(e)).append(", ")
                    .append(ExceptionUtils.getRootCauseMessage(e)).append("\n")
                    .append(ExceptionUtils.getFullStackTrace(e)).toString());
            logger.severe("Shutting down due to unexpected exception..");
            System.exit(23);
        }
    });

    logger.info("Created new Thread: " + name);

    return t;
}

From source file:edu.umn.cs.spatialHadoop.util.Parallel.java

public static <T> List<T> forEach(int start, int end, RunnableRange<T> r, int parallelism)
        throws InterruptedException {
    Vector<T> results = new Vector<T>();
    if (end <= start)
        return results;
    final Vector<Throwable> exceptions = new Vector<Throwable>();
    Thread.UncaughtExceptionHandler h = new Thread.UncaughtExceptionHandler() {
        public void uncaughtException(Thread th, Throwable ex) {
            exceptions.add(ex);//www . j  a v a 2  s.c om
        }
    };

    // Put an upper bound on parallelism to avoid empty ranges
    if (parallelism > (end - start))
        parallelism = end - start;
    if (parallelism == 1) {
        // Avoid creating threads
        results.add(r.run(start, end));
    } else {
        LOG.info("Creating " + parallelism + " threads");
        final int[] partitions = new int[parallelism + 1];
        for (int i_thread = 0; i_thread <= parallelism; i_thread++)
            partitions[i_thread] = i_thread * (end - start) / parallelism + start;
        final Vector<RunnableRangeThread<T>> threads = new Vector<RunnableRangeThread<T>>();
        for (int i_thread = 0; i_thread < parallelism; i_thread++) {
            RunnableRangeThread<T> thread = new RunnableRangeThread<T>(r, partitions[i_thread],
                    partitions[i_thread + 1]);
            thread.setUncaughtExceptionHandler(h);
            threads.add(thread);
            threads.lastElement().start();
        }
        for (int i_thread = 0; i_thread < parallelism; i_thread++) {
            threads.get(i_thread).join();
            results.add(threads.get(i_thread).getResult());
        }
        if (!exceptions.isEmpty())
            throw new RuntimeException(exceptions.size() + " unhandled exceptions", exceptions.firstElement());
    }
    return results;
}

From source file:com.spotify.helios.system.AgentStateDirConflictTest.java

@Before
public void setup() throws Exception {
    zk = new ZooKeeperTestingServerManager();
    dueh = Thread.getDefaultUncaughtExceptionHandler();

    Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
        @Override/*from  w w  w . j  a  v a  2 s .co  m*/
        public void uncaughtException(final Thread t, final Throwable e) {
        }
    });

    stateDir = Files.createTempDirectory("helios-agent-conflict-test");

    first = makeAgent("first");
    second = makeAgent("second");
}

From source file:com.github.dozermapper.core.DozerBeanMapperTest.java

@Before
public void setUp() {
    // todo the test should be redesigned once DozerBeanMapper is immutable #434
    mapper = DozerBeanMapperBuilder.buildDefault();
    exceptions = new ArrayList<>();
    Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
        public void uncaughtException(Thread t, Throwable e) {
            exceptions.add(e);/*from w  w w  . j a  v  a2 s.c om*/
        }
    });
}

From source file:com.apptentive.android.sdk.module.engagement.interaction.InteractionManager.java

public static void asyncFetchAndStoreInteractions(final Context context) {

    if (!isPollForInteractions(context)) {
        Log.v("Interaction polling is disabled.");
        return;/* ww w  .j a v a2 s .c  o m*/
    }

    if (hasCacheExpired(context)) {
        Log.d("Interaction cache has expired. Fetching new interactions.");
        Thread thread = new Thread() {
            public void run() {
                fetchAndStoreInteractions(context);
            }
        };
        Thread.UncaughtExceptionHandler handler = new Thread.UncaughtExceptionHandler() {
            @Override
            public void uncaughtException(Thread thread, Throwable throwable) {
                Log.w("UncaughtException in InteractionManager.", throwable);
                MetricModule.sendError(context.getApplicationContext(), throwable, null, null);
            }
        };
        thread.setUncaughtExceptionHandler(handler);
        thread.setName("Apptentive-FetchInteractions");
        thread.start();
    } else {
        Log.d("Interaction cache has not expired. Using existing interactions.");
    }
}

From source file:org.apache.hadoop.hdfs.TestFileCreationEmpty.java

/**
 * This test creates three empty files and lets their leases expire.
 * This triggers release of the leases. 
 * The empty files are supposed to be closed by that 
 * without causing ConcurrentModificationException.
 *///  www.  j a  v  a2  s .  c om
public void testLeaseExpireEmptyFiles() throws Exception {
    final Thread.UncaughtExceptionHandler oldUEH = Thread.getDefaultUncaughtExceptionHandler();
    Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
        public void uncaughtException(Thread t, Throwable e) {
            if (e instanceof ConcurrentModificationException) {
                LeaseManager.LOG.error("t=" + t, e);
                isConcurrentModificationException = true;
            }
        }
    });

    LOG.info("testLeaseExpireEmptyFiles start");
    final long leasePeriod = 1000;
    final int DATANODE_NUM = 3;

    final Configuration conf = new HdfsConfiguration();
    conf.setInt(DFSConfigKeys.DFS_NAMENODE_HEARTBEAT_RECHECK_INTERVAL_KEY, 1000);
    conf.setInt(DFSConfigKeys.DFS_HEARTBEAT_INTERVAL_KEY, 1);

    // create cluster
    MiniDFSCluster cluster = new MiniDFSCluster.Builder(conf).numDataNodes(DATANODE_NUM).build();
    try {
        cluster.waitActive();
        DistributedFileSystem dfs = (DistributedFileSystem) cluster.getFileSystem();

        // create a new file.
        TestFileCreation.createFile(dfs, new Path("/foo"), DATANODE_NUM);
        TestFileCreation.createFile(dfs, new Path("/foo2"), DATANODE_NUM);
        TestFileCreation.createFile(dfs, new Path("/foo3"), DATANODE_NUM);

        // set the soft and hard limit to be 1 second so that the
        // namenode triggers lease recovery
        cluster.setLeasePeriod(leasePeriod, leasePeriod);
        // wait for the lease to expire
        try {
            Thread.sleep(5 * leasePeriod);
        } catch (InterruptedException e) {
        }

        assertFalse(isConcurrentModificationException);
    } finally {
        Thread.setDefaultUncaughtExceptionHandler(oldUEH);
        cluster.shutdown();
    }
}

From source file:com.hp.mqm.atrf.Main.java

private static void setUncaughtExceptionHandler() {
    Thread.currentThread().setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
        public void uncaughtException(Thread t, Throwable e) {
            logger.error(e.getMessage(), e);
        }/*from   w  w  w  .j  ava  2  s  . c om*/
    });
}