Exception vs Error
Unexpected vs expected
Last updated
Unexpected vs expected
Last updated
In general, and with regards to situations that occur during run-time, I distinguish between Error and Exception.
An Error is something expected. A situation that you must expect to happen and where your "code" implements the right mitigation actions.
For example, imagine you want to Upsert (update or insert) a customer record, and you call a REST Service to GetCustomerByID() to check if the customer already exists. The REST Service responds http-status 404-NOT_FOUND in case the customer does not exists. In this situation, we consider the 404 to be an Error situation that must be considered as part of your execution path, to be able to perform an Update or Insert operation.
An Exception is something unexpected - a situation where your code does not have the right "answer" and where the code cannot complete the requested logic. An Exception interrupts to execution which cannot come to the expected end. It is a MUST that you handle these unexpected situations if you do not want your code behave in an unpredictable way.
Imagine you want to transfer an invoice from system A to B. Your expectation is (green path = requested functionality) you send the invoice to system B - and done! It is very unlikely (unexpected) that system B rejects the invoice for any reason, however it may happen!
If you do not design for the unexpected, the invoice (that hasn't reached its destination) is lost because the process simply stopped executing after the reject without any notice. If you design for the unexpected, your code will end up in an exception handler, where it can handle the exception and terminate gracefully, for example, by notifying the sender about the reject.
Note: With regards to the example above, if GetCustomerByID() always returned http-200 OK, also when the customer does not exist, a NOT_FOUND response would then be an unexpected situation! Whether http-404 is an Error or an Exception depends on your context and the question: do you expect it to happen, or not?
Errors are handled when and where they occur. Errors keep the code on the green path and let the business functionality complete successfully.
In any case, your code cannot continue on the green path (this is an Exception [and you may throw it]). Exceptions lead to an unexpected end of processing (of a single document or the process itself).