Example usage for java.lang Thread setDefaultUncaughtExceptionHandler

List of usage examples for java.lang Thread setDefaultUncaughtExceptionHandler

Introduction

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

Prototype

public static void setDefaultUncaughtExceptionHandler(UncaughtExceptionHandler eh) 

Source Link

Document

Set the default handler invoked when a thread abruptly terminates due to an uncaught exception, and no other handler has been defined for that thread.

Usage

From source file:pl.otros.logview.gui.LogViewMainFrame.java

public LogViewMainFrame(DataConfiguration c) throws InitializationException {
    super();/*from   w  w w . jav a 2 s .  co  m*/
    this.configuration = c;
    this.setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
    String title = "OtrosLogViewer";
    try {
        title += ' ' + VersionUtil.getRunningVersion();
    } catch (Exception e) {
        LOGGER.warning("Can't load version of running OLV");
    }
    this.setTitle(title);
    try {
        String iconPath = "img/otros/logo16.png";
        if (System.getProperty("os.name").contains("Linux")) {
            iconPath = "img/otros/logo64.png";
        }
        BufferedImage icon = ImageIO.read(this.getClass().getClassLoader().getResourceAsStream(iconPath));
        this.setIconImage(icon);
    } catch (Exception e1) {
        LOGGER.warning("Can't load icon: " + e1.getMessage());
    }
    Exception modalDisplayException = null;
    // If non-terminal load problem occurs, queue to display for user on
    // top of the app UI.
    try {
        OtrosSplash.setMessage("Loading plugins");
        LvDynamicLoader.getInstance().setStatusObserver(OtrosSplash.getSplashStatusObserver());
        LvDynamicLoader.getInstance().loadAll();
        OtrosSplash.setMessage("Loading plugins loaded");
    } catch (IOException e) {
        LOGGER.severe("Problem with loading automatic markers, filter or log importers: " + e.getMessage());
        modalDisplayException = e;
    } catch (InitializationException ie) {
        // Details should have been logged at lower level
        modalDisplayException = ie;
    }
    OtrosSplash.setMessage("Initializing GUI");
    allPluginables = AllPluginables.getInstance();
    logImportersContainer = allPluginables.getLogImportersContainer();
    messageColorizercontainer = allPluginables.getMessageColorizers();
    searchResultColorizer = (SearchResultColorizer) messageColorizercontainer
            .getElement(SearchResultColorizer.class.getName());
    cardLayout = new CardLayout();
    cardLayoutPanel = new JPanel(cardLayout);
    JLabel statusLabel = new JLabel(" ");
    observer = new JLabelStatusObserver(statusLabel);
    logsTabbedPane = new JTabbedPane();
    enableDisableComponetsForTabs = new EnableDisableComponetsForTabs(logsTabbedPane);
    logsTabbedPane.addChangeListener(enableDisableComponetsForTabs);

    otrosApplication = new OtrosApplication();
    otrosApplication.setAllPluginables(AllPluginables.getInstance());
    otrosApplication.setApplicationJFrame(this);
    otrosApplication.setConfiguration(configuration);
    otrosApplication.setjTabbedPane(logsTabbedPane);
    otrosApplication.setStatusObserver(observer);
    otrosApplication.setOtrosVfsBrowserDialog(new JOtrosVfsBrowserDialog(getVfsFavoritesConfiguration()));
    otrosApplication.setServices(new ServicesImpl(otrosApplication));
    SingleInstanceRequestResponseDelegate.getInstance().setOtrosApplication(otrosApplication);
    ToolTipManager.sharedInstance().setDismissDelay(5000);

    JProgressBar heapBar = new JProgressBar();
    heapBar.setPreferredSize(new Dimension(190, 15));
    new Thread(new MemoryUsedStatsUpdater(heapBar, 1500), "MemoryUsedUpdater").start();
    JPanel statusPanel = new JPanel(new MigLayout("fill", "[fill, push, grow][right][right]", "[]"));
    statusPanel.add(statusLabel);
    final JButton ideConnectedLabel = new JButton(Ide.IDEA.getIconDiscounted());
    statusPanel.add(ideConnectedLabel);
    statusPanel.add(new JButton(new SwitchAutoJump(otrosApplication)));
    statusPanel.add(heapBar);

    initMenu();
    initToolbar();
    addEmptyViewListener();
    addMenuBarReloadListener();
    otrosApplication.setSearchField(searchField);
    cardLayoutPanel.add(logsTabbedPane, CARD_LAYOUT_LOGS_TABLE);
    EmptyViewPanel emptyViewPanel = new EmptyViewPanel(otrosApplication);
    final JScrollPane jScrollPane = new JScrollPane(emptyViewPanel, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
            JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
    SwingUtilities.invokeLater(new Runnable() {
        @Override
        public void run() {
            jScrollPane.getVerticalScrollBar().setValue(0);
        }
    });
    cardLayoutPanel.add(jScrollPane, CARD_LAYOUT_EMPTY);
    cardLayout.show(cardLayoutPanel, CARD_LAYOUT_EMPTY);
    enableDisableComponetsForTabs.stateChanged(null);
    Container cp = getContentPane();
    cp.setLayout(new BorderLayout());
    cp.add(toolBar, BorderLayout.NORTH);
    cp.add(cardLayoutPanel, BorderLayout.CENTER);
    cp.add(statusPanel, BorderLayout.SOUTH);
    initGlobalHotKeys();
    initPosition();
    if (configuration.getBoolean(ConfKeys.LOAD_EXPERIMENTAL_FEATURES, false)) {
        initExperimental();
    }
    setTransferHandler(new DragAndDropFilesHandler(otrosApplication));
    initPlugins();
    OtrosSplash.hide();
    setVisible(true);
    if (modalDisplayException != null)
        JOptionPane.showMessageDialog(this,
                "Problem with loading automatic markers," + "filter or log importers:\n"
                        + modalDisplayException.getMessage(),
                "Initialization Error", JOptionPane.ERROR_MESSAGE);
    // Check new version on start
    if (c.getBoolean(ConfKeys.VERSION_CHECK_ON_STARTUP, true)) {
        new ChekForNewVersionOnStartupAction(otrosApplication).actionPerformed(null);
    }
    new TipOfTheDay(c).showTipOfTheDayIfNotDisabled(this);
    Toolkit.getDefaultToolkit().getSystemEventQueue().push(new EventQueueProxy());
    ListUncaughtExceptionHandlers listUncaughtExceptionHandlers = new ListUncaughtExceptionHandlers(//
            new LoggingExceptionHandler(), //
            new ShowErrorDialogExceptionHandler(otrosApplication), //
            new StatusObserverExceptionHandler(observer));
    Thread.setDefaultUncaughtExceptionHandler(listUncaughtExceptionHandlers);
    ListeningScheduledExecutorService listeningScheduledExecutorService = otrosApplication.getServices()
            .getTaskSchedulerService().getListeningScheduledExecutorService();
    listeningScheduledExecutorService.scheduleAtFixedRate(
            new IdeAvailabilityCheck(ideConnectedLabel, otrosApplication.getServices().getJumpToCodeService()),
            5, 5, TimeUnit.SECONDS);
    ideConnectedLabel.addActionListener(new IdeIntegrationConfigAction(otrosApplication));
}

From source file:org.ut.biolab.medsavant.MedSavantServlet.java

private void setExceptionHandler() {
    Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
        @Override//from   w  w w  .j a va 2s .co m
        public void uncaughtException(Thread t, Throwable e) {
            LOG.info("Global exception handler caught: " + t.getName() + ": " + e);

            if (e instanceof InvocationTargetException) {
                e = ((InvocationTargetException) e).getCause();
            }

            if (e instanceof SessionExpiredException) {
                SessionExpiredException see = (SessionExpiredException) e;
                LOG.error("Session expired exception: " + see.toString());
                return;
            }
            e.printStackTrace();
        }
    });
}

From source file:pipeline.A0PipeLine_Manager.java

public static int setup(String arg, ImagePlus img) {
    Thread.setDefaultUncaughtExceptionHandler(new DefaultExceptionHandler());
    return 0;/*from   ww  w.j a  v a2  s. c  om*/
}

From source file:de.huxhorn.lilith.Lilith.java

private static void startLilith(String appTitle) {
    final Logger logger = LoggerFactory.getLogger(Lilith.class);

    uncaughtExceptionHandler = new UncaughtExceptionHandler();

    Thread.setDefaultUncaughtExceptionHandler(uncaughtExceptionHandler);

    // preventing duplicate instances...
    try {/*w  w  w  .  j  a  va  2s  . c  o  m*/
        JUnique.acquireLock(Lilith.class.getName(), Lilith::handleJUniqueMessage);
    } catch (AlreadyLockedException e) {
        if (logger.isInfoEnabled())
            logger.info("Detected running instance, quitting.");
        String result = JUnique.sendMessage(Lilith.class.getName(), "Show");
        if (logger.isDebugEnabled())
            logger.debug("JUnique result: {}", result);
        return;
    }
    // ok, we are the first instance this user has started...

    // install uncaught exception handler on event thread.
    EventQueue.invokeLater(() -> Thread.currentThread().setUncaughtExceptionHandler(uncaughtExceptionHandler));

    startUI(appTitle);
}

From source file:com.cognizant.trumobi.em.Email.java

@Override
public void onCreate() {
    super.onCreate();
    /*BugSenseHandler.initAndStartSession(this.getApplicationContext(),
    "377266e1");*//* www .  j av a2 s  .  co m*/
    Thread.setDefaultUncaughtExceptionHandler(
            new PersonaExceptionHandler(this, Thread.getDefaultUncaughtExceptionHandler()));
    EmPreferences prefs = EmPreferences.getPreferences(this);
    DEBUG = prefs.getEnableDebugLogging();
    DEBUG_SENSITIVE = prefs.getEnableSensitiveLogging();
    setTempDirectory(this);
    appContext = getApplicationContext();
    checkBugSenseEnableStatus();
    // Reset all accounts to default visible window
    EmEmController.getInstance(this).resetVisibleLimits();

    // Enable logging in the EAS service, so it starts up as early as
    // possible.
    EmDebug.updateLoggingFlags(this);

    // Listen Phone Call Changes
    DialerParentActivity listenState = new DialerParentActivity();
    callListner = listenState.new PhoneCallListener(getAppContext());
    telMgr = (TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE);
    telMgr.listen(callListner, PhoneCallListener.LISTEN_CALL_STATE);
    //Broadcast
    registerBroadcastReceiver();

}

From source file:com.vonglasow.michael.satstat.ui.MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    defaultUEH = Thread.getDefaultUncaughtExceptionHandler();

    Thread.setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandler() {
        public void uncaughtException(Thread t, Throwable e) {
            Context c = getApplicationContext();
            File dumpDir = c.getExternalFilesDir(null);
            DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss", Locale.ROOT);
            fmt.setTimeZone(TimeZone.getTimeZone("UTC"));
            String fileName = String.format("satstat-%s.log", fmt.format(new Date(System.currentTimeMillis())));

            File dumpFile = new File(dumpDir, fileName);
            PrintStream s;//from   w  w  w  .ja  v a 2  s  . c  o m
            try {
                InputStream buildInStream = getResources().openRawResource(R.raw.build);
                s = new PrintStream(dumpFile);
                s.append("SatStat build: ");

                int i;
                try {
                    i = buildInStream.read();
                    while (i != -1) {
                        s.write(i);
                        i = buildInStream.read();
                    }
                    buildInStream.close();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }

                s.append("\n\n");
                e.printStackTrace(s);
                s.flush();
                s.close();

                Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
                Uri contentUri = Uri.fromFile(dumpFile);
                mediaScanIntent.setData(contentUri);
                c.sendBroadcast(mediaScanIntent);
            } catch (FileNotFoundException e2) {
                e2.printStackTrace();
            }
            defaultUEH.uncaughtException(t, e);
        }
    });

    mSharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
    mSharedPreferences.registerOnSharedPreferenceChangeListener(this);
    prefUnitType = mSharedPreferences.getBoolean(Const.KEY_PREF_UNIT_TYPE, prefUnitType);
    prefKnots = mSharedPreferences.getBoolean(Const.KEY_PREF_KNOTS, prefKnots);
    prefCoord = Integer
            .valueOf(mSharedPreferences.getString(Const.KEY_PREF_COORD, Integer.toString(prefCoord)));
    prefUtc = mSharedPreferences.getBoolean(Const.KEY_PREF_UTC, prefUtc);
    prefCid = mSharedPreferences.getBoolean(Const.KEY_PREF_CID, prefCid);
    prefCid2 = mSharedPreferences.getBoolean(Const.KEY_PREF_CID2, prefCid2);
    prefWifiSort = Integer
            .valueOf(mSharedPreferences.getString(Const.KEY_PREF_WIFI_SORT, Integer.toString(prefWifiSort)));
    prefMapOffline = mSharedPreferences.getBoolean(Const.KEY_PREF_MAP_OFFLINE, prefMapOffline);
    prefMapPath = mSharedPreferences.getString(Const.KEY_PREF_MAP_PATH, prefMapPath);

    ActionBar actionBar = getSupportActionBar();

    setContentView(R.layout.activity_main);

    // Find out default screen orientation
    Configuration config = getResources().getConfiguration();
    WindowManager wm = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
    int rot = wm.getDefaultDisplay().getRotation();
    isWideScreen = (config.orientation == Configuration.ORIENTATION_LANDSCAPE
            && (rot == Surface.ROTATION_0 || rot == Surface.ROTATION_180)
            || config.orientation == Configuration.ORIENTATION_PORTRAIT
                    && (rot == Surface.ROTATION_90 || rot == Surface.ROTATION_270));
    Log.d(TAG, "isWideScreen=" + Boolean.toString(isWideScreen));

    // Create the adapter that will return a fragment for each of the
    // primary sections of the app.
    mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());

    // Set up the ViewPager with the sections adapter.
    mViewPager = (ViewPager) findViewById(R.id.pager);
    mViewPager.setAdapter(mSectionsPagerAdapter);

    Context ctx = new ContextThemeWrapper(getApplication(), R.style.AppTheme);
    mTabLayout = new TabLayout(ctx);
    LinearLayout.LayoutParams mTabLayoutParams = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT,
            LayoutParams.WRAP_CONTENT);
    mTabLayout.setLayoutParams(mTabLayoutParams);

    for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
        TabLayout.Tab newTab = mTabLayout.newTab();
        newTab.setIcon(mSectionsPagerAdapter.getPageIcon(i));
        mTabLayout.addTab(newTab);
    }

    actionBar.setDisplayShowCustomEnabled(true);
    actionBar.setCustomView(mTabLayout);

    mTabLayout.setOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(mViewPager));
    mViewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(mTabLayout));

    // This is needed by the mapsforge library.
    AndroidGraphicFactory.createInstance(this.getApplication());

    // Get system services for event delivery
    locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
    sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
    mOrSensor = sensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION);
    mAccSensor = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
    mGyroSensor = sensorManager.getDefaultSensor(Sensor.TYPE_GYROSCOPE);
    mMagSensor = sensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);
    mLightSensor = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
    mProximitySensor = sensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY);
    mPressureSensor = sensorManager.getDefaultSensor(Sensor.TYPE_PRESSURE);
    mHumiditySensor = sensorManager.getDefaultSensor(Sensor.TYPE_RELATIVE_HUMIDITY);
    mTempSensor = sensorManager.getDefaultSensor(Sensor.TYPE_AMBIENT_TEMPERATURE);
    telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
    connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
}

From source file:net.sourceforge.entrainer.gui.EntrainerFX.java

private void init() {
    Thread.setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandler() {

        @Override/* www.jav a  2  s .co m*/
        public void uncaughtException(Thread arg0, Throwable arg1) {
            GuiUtil.handleProblem(arg1);
        }
    });

    intervalMenu = new IntervalMenu();
    control = new JSynSoundControl();
    masterLevelController = new MasterLevelController(control);
    initMediator();
    wireButtons();
    layoutComponents();
    addWindowListener(new WindowAdapter() {
        public void windowClosing(WindowEvent e) {
            exitPressed();
        }
    });

    initButtonIcons();
    createPanner();
    addMenu();
    initSettings();

    addMouseListener(new MouseAdapter() {
        public void mouseClicked(MouseEvent e) {
            if (e.isControlDown() && e.getClickCount() == 1) {
                openBrowser(getLocalDocAddress());
            }
        }
    });
}

From source file:org.apache.log4j.chainsaw.LogUI.java

/**
 * Creates, activates, and then shows the Chainsaw GUI, optionally showing
 * the splash screen, and using the passed shutdown action when the user
 * requests to exit the application (if null, then Chainsaw will exit the vm)
 *
 * @param model/*from   w w  w .  jav a 2  s .  c  o m*/
 * @param newShutdownAction
 *                    DOCUMENT ME!
 */
public static void createChainsawGUI(ApplicationPreferenceModel model, Action newShutdownAction) {

    if (model.isOkToRemoveSecurityManager()) {
        MessageCenter.getInstance()
                .addMessage("User has authorised removal of Java Security Manager via preferences");
        System.setSecurityManager(null);
        // this SHOULD set the Policy/Permission stuff for any
        // code loaded from our custom classloader.  
        // crossing fingers...
        Policy.setPolicy(new Policy() {

            public void refresh() {
            }

            public PermissionCollection getPermissions(CodeSource codesource) {
                Permissions perms = new Permissions();
                perms.add(new AllPermission());
                return (perms);
            }
        });
    }

    final LogUI logUI = new LogUI();
    logUI.applicationPreferenceModel = model;

    if (model.isShowSplash()) {
        showSplash(logUI);
    }
    logUI.cyclicBufferSize = model.getCyclicBufferSize();
    logUI.pluginRegistry = repositoryExImpl.getPluginRegistry();

    logUI.handler = new ChainsawAppenderHandler();
    logUI.handler.addEventBatchListener(logUI.new NewTabEventBatchReceiver());

    /**
     * TODO until we work out how JoranConfigurator might be able to have
     * configurable class loader, if at all.  For now we temporarily replace the
     * TCCL so that Plugins that need access to resources in 
     * the Plugins directory can find them (this is particularly
     * important for the Web start version of Chainsaw
     */
    //configuration initialized here
    logUI.ensureChainsawAppenderHandlerAdded();
    logger = LogManager.getLogger(LogUI.class);

    //set hostname, application and group properties which will cause Chainsaw and other apache-generated
    //logging events to route (by default) to a tab named 'chainsaw-log'
    PropertyRewritePolicy policy = new PropertyRewritePolicy();
    policy.setProperties("hostname=chainsaw,application=log,group=chainsaw");

    RewriteAppender rewriteAppender = new RewriteAppender();
    rewriteAppender.setRewritePolicy(policy);

    Enumeration appenders = Logger.getLogger("org.apache").getAllAppenders();
    if (!appenders.hasMoreElements()) {
        appenders = Logger.getRootLogger().getAllAppenders();
    }
    while (appenders.hasMoreElements()) {
        Appender nextAppender = (Appender) appenders.nextElement();
        rewriteAppender.addAppender(nextAppender);
    }
    Logger.getLogger("org.apache").removeAllAppenders();
    Logger.getLogger("org.apache").addAppender(rewriteAppender);
    Logger.getLogger("org.apache").setAdditivity(false);

    //commons-vfs uses httpclient for http filesystem support, route this to the chainsaw-log tab as well
    appenders = Logger.getLogger("httpclient").getAllAppenders();
    if (!appenders.hasMoreElements()) {
        appenders = Logger.getRootLogger().getAllAppenders();
    }
    while (appenders.hasMoreElements()) {
        Appender nextAppender = (Appender) appenders.nextElement();
        rewriteAppender.addAppender(nextAppender);
    }
    Logger.getLogger("httpclient").removeAllAppenders();
    Logger.getLogger("httpclient").addAppender(rewriteAppender);
    Logger.getLogger("httpclient").setAdditivity(false);

    //set the commons.vfs.cache logger to info, since it can contain password information
    Logger.getLogger("org.apache.commons.vfs.cache").setLevel(Level.INFO);

    Thread.setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandler() {
        public void uncaughtException(Thread t, Throwable e) {
            e.printStackTrace();
            logger.error("Uncaught exception in thread " + t, e);
        }
    });

    String config = configurationURLAppArg;
    if (config != null) {
        logger.info("Command-line configuration arg provided (overriding auto-configuration URL) - using: "
                + config);
    } else {
        config = model.getConfigurationURL();
    }

    if (config != null && (!config.trim().equals(""))) {
        config = config.trim();
        try {
            URL configURL = new URL(config);
            logger.info("Using '" + config + "' for auto-configuration");
            logUI.loadConfigurationUsingPluginClassLoader(configURL);
        } catch (MalformedURLException e) {
            logger.error("Initial configuration - failed to convert config string to url", e);
        } catch (IOException e) {
            logger.error("Unable to access auto-configuration URL: " + config);
        }
    }

    //register a listener to load the configuration when it changes (avoid having to restart Chainsaw when applying a new configuration)
    //this doesn't remove receivers from receivers panel, it just triggers DOMConfigurator.configure.
    model.addPropertyChangeListener("configurationURL", new PropertyChangeListener() {
        public void propertyChange(PropertyChangeEvent evt) {
            String newConfiguration = evt.getNewValue().toString();
            if (newConfiguration != null && !(newConfiguration.trim().equals(""))) {
                newConfiguration = newConfiguration.trim();
                try {
                    logger.info("loading updated configuration: " + newConfiguration);
                    URL newConfigurationURL = new URL(newConfiguration);
                    File file = new File(newConfigurationURL.toURI());
                    if (file.exists()) {
                        logUI.loadConfigurationUsingPluginClassLoader(newConfigurationURL);
                    } else {
                        logger.info("Updated configuration but file does not exist");
                    }
                } catch (MalformedURLException e) {
                    logger.error("Updated configuration - failed to convert config string to URL", e);
                } catch (URISyntaxException e) {
                    logger.error("Updated configuration - failed to convert config string to URL", e);
                }
            }
        }
    });

    LogManager.getRootLogger().setLevel(Level.TRACE);
    EventQueue.invokeLater(new Runnable() {
        public void run() {
            logUI.activateViewer();
        }
    });

    logger.info("SecurityManager is now: " + System.getSecurityManager());

    if (newShutdownAction != null) {
        logUI.setShutdownAction(newShutdownAction);
    } else {
        logUI.setShutdownAction(new AbstractAction() {
            public void actionPerformed(ActionEvent e) {
                System.exit(0);
            }
        });
    }
}

From source file:org.apache.qpid.server.Main.java

protected void setExceptionHandler() {
    Thread.UncaughtExceptionHandler handler = null;
    String handlerClass = System.getProperty("qpid.broker.exceptionHandler");
    if (handlerClass != null) {
        try {/*from   w w  w . j a va  2  s  .c  o m*/
            handler = (Thread.UncaughtExceptionHandler) Class.forName(handlerClass).newInstance();
        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException
                | ClassCastException e) {

        }
    }

    if (handler == null) {
        handler = new Thread.UncaughtExceptionHandler() {
            public void uncaughtException(final Thread t, final Throwable e) {
                boolean continueOnError = Boolean.getBoolean("qpid.broker.exceptionHandler.continue");
                try {
                    System.err.println(
                            "########################################################################");
                    System.err.println("#");
                    System.err.print("# Unhandled Exception ");
                    System.err.print(e.toString());
                    System.err.print(" in Thread ");
                    System.err.println(t.getName());
                    System.err.println("#");
                    System.err.println(continueOnError
                            ? "# Forced to continue by JVM setting 'qpid.broker.exceptionHandler.continue'"
                            : "# Exiting");
                    System.err.println("#");
                    System.err.println(
                            "########################################################################");
                    e.printStackTrace(System.err);

                    Logger logger = LoggerFactory.getLogger("org.apache.qpid.server.Main");
                    logger.error("Uncaught exception, " + (continueOnError ? "continuing." : "shutting down."),
                            e);
                } finally {
                    if (!continueOnError) {
                        Runtime.getRuntime().halt(1);
                    }
                }

            }
        };

        Thread.setDefaultUncaughtExceptionHandler(handler);
    }
}

From source file:com.haulmont.cuba.desktop.App.java

protected void initExceptionHandling() {
    Thread.setDefaultUncaughtExceptionHandler(this::handleException);

    System.setProperty("sun.awt.exception.handler", "com.haulmont.cuba.desktop.exception.AWTExceptionHandler");
}