Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to to catch all possible errors/exception?

I have a Java Swing program with many classes. I do use try-catchs where they are required, but no where else. I also have a logger class, which writes to a file when an exception is caught. It prints out the stack trace and the message.

I want to be able to log every exception but without putting try-catch's everywhere. Is this possible?

-- EDIT (My main method) --

public class Bacon extends Thread implements UncaughtExceptionHandler {
    public static Bacon instance = null;
    private JFrame main;

    private Bacon() {
        main = new JFrame("Bacon");
        main.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
        main.addWindowListener(new WindowEventHandler());
        setLAF();
        main.setSize(Constants.MAIN_DIMENSION);
        main.setLocationRelativeTo(null);
        main.setExtendedState(JFrame.MAXIMIZED_BOTH);
        main.setIconImage(getIcon());
        setUserName();
        setUncaughtExceptionHandler(this);

        main.setJMenuBar(Menu.getInstance());
        main.setContentPane(getMainPanel());
        main.setVisible(true);
    }

    public static Bacon getInstance() {
        if(instance == null)
            instance = new Bacon();

        return instance;
    }

    private JPanel getMainPanel() {
        JPanel main = new JPanel(new BorderLayout());

        main.add(Tabs.getInstance(), BorderLayout.CENTER);
        main.add(StatusBar.getInstance(), BorderLayout.SOUTH);

        return main;
    }

    .
    .
    .
    .
    .
    .
    .

    public static void main(String[] args) {
        try {
            getInstance();
        } catch (Throwable t) {
            ErrorLogging.log(t.getStackTrace(), t.getMessage());
        }
    }

    @Override
    public void uncaughtException(Thread t, Throwable e) {
        ErrorLogging.log(e.getStackTrace(), e.getMessage());
    }
}
like image 776
samwell Avatar asked Dec 02 '22 22:12

samwell


1 Answers

Absolutely!

Look at the Thread class' method setDefaultUncaughtExceptionHandler.

Thread.setDefaultUncaughtExceptionHandler

like image 185
Jose Avatar answered Dec 24 '22 01:12

Jose