File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Swing / AWT / SWT and the fly likes Best practice for error handling in Swing Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Swing / AWT / SWT
Bookmark "Best practice for error handling in Swing" Watch "Best practice for error handling in Swing" New topic

Best practice for error handling in Swing

Colin Yates
Ranch Hand

Joined: Dec 16, 2004
Posts: 31
Hi all,

In the wonderful world of server side development, any exceptions you don't want to deal with propogate up to the container.

Is there an equivalent "thing" in Swing?

What is the best practice for handling exceptions in a Swing GUI? At the moment there are lots of catch (Exception e) { System.out... } (yeah, I know, it happened before I arrived )

What I want is to get to a point where all exceptions propogate up to a central handler.

Hope that makes sense
Joe Ess

Joined: Oct 29, 2001
Posts: 9189

Not really. Swing is a pretty open environment compared to a J2EE container. What I've found that works for me is to make the top-level container, usually a JFrame, a listener for a custom ExceptionEvent. When he receives one of these events the frame displays a dialog with an error message and a stack trace. The controller, which initially creates the frame, passes a reference around to all the interested classes in the guise of the interface ExceptionListener. Whenever an exception is caught they invoke the ExceptionListener method to report it.
You will, of course, have to use some judgement on what to display. Let's say you wrote an editor and the user requests a file that doesn't exist. You'd want to catch the FileNotFound exception and display a dialog that prompts the user to either create a new file or choose a different one. I'd handle that through some other mechanism than the above, which I see as reporting fatal exceptions or exceptions that "shouldn't occur" via a catch-all exception handler.

[How To Ask Questions On JavaRanch]
I agree. Here's the link:
subject: Best practice for error handling in Swing
It's not a secret anymore!