When it comes to exception handling, there are many guidelines and best practices on the web. On of them is to throw early, catch late, or even Don't Catch. So when facing an exception, the current use case would be abandoned by letting the exception bubble up, until some global exception handler catches it, logs it and shows an error to the user.
I like this approach and I would like to refactor our application according to it. However, it is a desktop application (Java Swing), and I am not sure whether the approach is more applicable to web applications and less to desktop applications. For example, when Victor Rentea says the following, it is specific for web apps:
In web apps today, when handling exceptions we don't recover, we die!
He doesn't give any reason why he talks only about web apps. My own understanding is that for web applications, it is easier to achieve failure atomicity, i.e. leaving the application in a consistent state in case of failures.
Processing a request on the server typically does not alter the state, except in a DB, and that can be easily made atomic using transactions. When encountering an exception, the transaction is rolled back, and an error response indicating the failure is sent to the client. The server remains in the same state as it was before the request.
In a desktop application things can be very different. There can be long running background tasks constantly updating the UI to show intermediate progress. Or there could be some low level "drawing" logic, placing individual shapes like circles and rectangles on the screen (e.g. paint()
in Java Swing). Aborting such a workflow somewhere in the middle very likely leaves the application or the UI in an inconsistent state.
Maybe it is possible to improve failure atomicity by applying the Functional Core, Imperative Shell pattern, but it is hard to enforce in frameworks which are not designed for functional programming such as Java Swing.
So what are some best practices for exception handling that are applicable to desktop applications? Is it still Throw Early, Catch Late, only that late is as late as possible but not later, which is earlier than in web applications? How can one find the "latest" places where exceptions must be catched and enforce that they are catched indeed?
Or are there any other best practices specific for desktop applications? As I said, I am using Java Swing, but that shouldn't be relevant.