2 ms·
The best use of exceptions in java that I have seen in production is when an exception is used to roll back a database transaction or when the web layer is able
by johnwatson11218 10y ago
The best use of exceptions in java that I have seen in production is when an exception is used to roll back a database transaction or when the web layer is able to catch all exceptions, log them, and then redirect the end user to a nice looking page telling something went wrong.
Another anti-pattern is subclassing Exceptions to have things like "UserNameInUse" exceptions during a sign up path to indicate that a selected username is not unique in the db. This becomes a poor man's message passing implementation. Using an exception to signal that is very inefficient as the exception has the entire stack trace as part of its data.
- barrkel 10y agoUsing an exception to signal a semantic error is only expensive if the language implementer has made that expensive. Technically, all the exception throw needs do is pop stack frames until it finds a handler. Getting a stack trace is optional, but keeping track of the return addresses (pushed by the CPU's call instruction) is sufficient to materialize that on demand. An array of integers isn't expensive either. I don't believe transactional programs using exceptions for rollback is an anti-pattern. It's not the best pattern - a transactional language, with transactional data structures, is much harder to get wrong - but it's not worst, not by a long shot.
- johnwatson11218 10y agosorry - I didn't mean to indicate that using transactions to signal a roll back is an anit-pattern. I started out that comment listing good things I had see exceptions used for. Then that example of the userNameInUse exception came to mind. I realize my choice of words made that less than clear.