Handling exceptions in a Swing UI (low level to high level and exception wrapping)

风流意气都作罢 提交于 2019-12-06 06:58:38

To catch NullPointerException (or any RuntimeException for that matter) as well as your IOExceptionjust catch the most general exception type:

try {
   dataService.exportData(list, selectedFile);
} catch (Exception e) {
   UiUtils.showError(new ApplicationException(e), e );
} finally {
  ...
}

You can wrap the original exception into your ApplicationException by adding it as a "cause" parameter to the constructor, e.g.:

public class ApplicationException extends RuntimeException {

   public ApplicationException(Exception cause) {
       super(cause);
   }

   ...
}

Then the original exception would be always available via the getCause() method.

If you program is not multithreaded, I wouldn't worry about simultaneous exceptions.

Users don't understand exceptions however nicely you coat or layer them ;-) Design every end-user targeted application in a way that there are none. And keep in mind that exceptions are for .. well .. exceptional state, nothing else.

F.i, empty selection is a perfectly valid state of a ui which allows to select something (and act on the selected item). If acting on empty-selection bubbles up as a NPE, the acting logic is incorrect - it must cope with any valid state. One option to cope might be to be disabled (as trashgod already suggested), another might be to show a warning label as long as there's nothing selected.

trashgod

For reference, nothing happens "simultaneously" on the event dispatch thread; the EventQueue enforces this. Moreover, Swing restarts the EDT on uncaught exceptions, but you can substitute your own handler, as shown here.

Addendum: @Sasha O has helpfully addressed the question directly. Alternatively, if you can arrange never to call the method with a null file handle, you can assert that fact as a precondition. See Programming With Assertions for details.

This leaves me wondering in what cases inputs should be checked before a method call or inside a method.

A lot depends on the design. Instead of dealing with "No file selected," disable affected controls until a valid file has been selected. Instead of dealing with "No data to export," filter files by type, size or content in the chooser dialog. You still have to deal with I/O faults, but that's inevitable, as they are external to your program.

Addendum: This raises the problem of helping the user understand why a control is disabled. Some applications use a status bar to show such information. A tooltip can help, as shown here, even on a disabled control.

You should not use assertions to check the parameters of a public method.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!