3 ms·
Are there guidelines for using exceptions in a correct way?
by the_arun 10y ago
Are there guidelines for using exceptions in a correct way?
- jacques_chester 10y agoMy thinking would be: First, don't catch exceptions unless you really can handle them. Swallowing and emitting a log line is not handling an exception. Second, and this is a corollary, only catch the exception classes you can handle. The classic antipatterns of swallow-and-log or swallow-and-convert are very frustrating. Swallow-and-log means that you don't see the true state of the world upon exceptional conditions arising. It is particularly harmful for gutting the usefulness of acceptance and unit testing. Swallow-and-convert means that you deny the rest of the stack a chance to properly handle the exception. You also suppress the information which checked exceptions provide to consumers of your method, converting something that can be solved at coding time into runtime error lotteries. Edit: per the comments below, my meaning for "swallow-and-convert" is the practice of turning meaningful exceptions into `RuntimeException` because it's "too hard" to add exceptions to consuming method signatures.
- sorokod 10y agoThere are cases where 'swallow-and-convert' is a reasonable thing to do. This often comes up in multi layer architectures where an exception from a lower layer makes no sense to a higher level and some sort of semantic conversion/translation is needed.
- jacques_chester 10y agoAgreed, I overlook that case. I've done exactly that in Java and Ruby.
- Hermel 10y agoIn large, layered software projects, the best solution can be "catch and wrap". In that case, the wrapping exception provides information about what went wrong, and the wrapped exception says why. For example, a CouldNotLoadImageException might wrap a JPegDecodingException or a CouldNotConnectException, depending on what went wrong underneath.
- mlvljr 10y agoA book even! I linked it below, as a level 1 comment.