Is a try-catch-finally clause appropriate for production code

coding-standards

While browsing around on SO, I came across an answer that suggested using a try-catch-finally clause to fix the problem he was having. (A rare bug that sometimes happened to his users). Someone commented that it was a valid solution, but he said it was not recommended for production code.

Is this true? Why is it not recommended for production code?

It seems perfectly valid to me if it is used for catching exceptions. In this context it was for an app and users are very discouraged from continuing if the app just crashes seemingly randomly.

He also mentioned that it could fail at anytime.

Is this true as well?

Best Answer

In the linked-to question/answer, the correct solution is to fix the fact that the unsubscribe code is called more than the subscribe code. If there is not time to fix it, then ignoring that specific exception may be a usable short-term workaround. But we all know what that means in production code.

In the general case, there is no clear "one size fits all" answer. There are valid arguments for and against exceptions in general, but the truth is that certain languages and libraries use them so you may as well get used to dealing with them effectively.

Sometimes an exception is relatively harmless and should trigger other behavior than a rethrow. For example, if input is not a valid number (e.g. java.lang.NumberFormatException) and cannot be stored in a numeric field. Maybe there is a way to indicate this on the UI and retry the input operation.

Sometimes an exception is much more serious (e.g. std::bad_alloc) and your program might want to catch it, perform some minimal cleanup, and rethrow to kill itself. In the case of a std::bad_alloc it would, of course, be a bad idea to allocate more memory during cleanup.

What this means is you really need to evaluate every situation. Think "what caused this exception to be thrown?" and "what is the realistic outcome during this exception handler?" It could mean anything from input validation catching something wrong, to something so severe there is no way to recover other than to write a stack trace or line number to the log and quit.

Related Topic