Java – handles unhandled exceptions in the GUI

I mainly write a small tool for technical proficient people, such as programmers, engineers and so on Since these tools usually improve over time, I know there will be unhandled exceptions that users won't mind I want users to send me backtracking so that I can check what happened and possibly improve the application

I usually do Wx python programming, but I have recently done some Java I have hooked the taskdialog class to thread Uncaughtexceptionhandler(), I'm very satisfied with the result In particular, it can catch and handle exceptions of any thread:

I have been doing similar work in Wx Python for a long time However:

>I had to write a decorator so that I could print exceptions from another thread. > Even in terms of function, the result is quite ugly

Here are the Java and wxpthon code, so you can see what I did:

Java:

import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.JButton;
import java.awt.GridBagLayout;
import java.awt.GridBagConstraints;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

import com.ezware.dialog.task.TaskDialogs;

public class SwingExceptionTest {

    private JFrame frame;

    public static void main(String[] args) {

        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        }
        catch (ClassNotFoundException e) {
        }
        catch (InstantiationException e) {
        }
        catch (illegalaccessexception e) {
        }
        catch (UnsupportedLookAndFeelException e) {
        }

        Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
            public void uncaughtException(Thread t,Throwable e) {
                TaskDialogs.showException(e);
            }
        });

        EventQueue.invokelater(new Runnable() {
            public void run() {
                try {
                    SwingExceptionTest window = new SwingExceptiontest();
                    window.frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    public SwingExceptiontest() {
        initialize();
    }

    private void initialize() {
        frame = new JFrame();
        frame.setBounds(100,100,600,400);
        frame.setDefaultCloSEOperation(JFrame.EXIT_ON_CLOSE);
        GridBagLayout gridBagLayout = new GridBagLayout();
        gridBagLayout.columnWidths = new int[]{0,0};
        gridBagLayout.rowHeights = new int[]{0,0};
        gridBagLayout.columnWeights = new double[]{0.0,Double.MIN_VALUE};
        gridBagLayout.rowWeights = new double[]{0.0,Double.MIN_VALUE};
        frame.getContentPane().setLayout(gridBagLayout);

        JButton btnNewButton = new JButton("Throw!");
        btnNewButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                onButton();
            }
        });
        GridBagConstraints gbc_btnNewButton = new GridBagConstraints();
        gbc_btnNewButton.gridx = 0;
        gbc_btnNewButton.gridy = 0;
        frame.getContentPane().add(btnNewButton,gbc_btnNewButton);
    }

    protected void onButton(){
        Thread worker = new Thread() {
            public void run() { 
                throw new RuntimeException("Exception!");
            }
        };
        worker.start();
    }

}

Of wxpthon:

import StringIO
import sys
import traceback
import wx
from wx.lib.delayedresult import startWorker


def thread_guard(f):
    def thread_guard_wrapper(*args,**kwargs) :
        try:
            r = f(*args,**kwargs)
            return r
        except Exception:
            exc = sys.exc_info()
            output = StringIO.StringIO()
            traceback.print_exception(exc[0],exc[1],exc[2],file=output)
            raise Exception("<THREAD GUARD>\n\n" + output.getvalue())
    return thread_guard_wrapper

@thread_guard
def thread_func():
    return 1 / 0

def thread_done(result):
    r = result.get()
    print r


class MainWindow(wx.Frame):
    def __init__(self,*args,**kwargs):
        wx.Frame.__init__(self,**kwargs)

        self.panel = wx.Panel(self)
        self.button = wx.Button(self.panel,label="Throw!")
        self.button.Bind(wx.EVT_BUTTON,self.OnButton)

        self.sizer = wx.@R_397_2419@Sizer()
        self.sizer.Add(self.button)

        self.panel.SetSizerAndFit(self.sizer)  
        self.Show()

    def OnButton(self,e):
        startWorker(thread_done,thread_func)

app = wx.App(True)
win = MainWindow(None,size=(600,400))
app.MainLoop()

The question now:

Can I easily do something similar to the Java solution in Wx Python? Or perhaps, is there a better way in Java or wxPython?

Solution

In Python, you can use sys Execpthook is set to the function to be called for an uncapped exception Then you don't need decorators. You can handle exceptions centrally in hook functions

Instead of just printing exception tracking text and letting it display in the stock stdout window, you can use it more intelligently, such as using a dialog box to display text and having controls that allow users to send error messages back to developers, ignore future errors, restart the application, or whatever you want

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>