- Expection handling
Expection handling is a
computer programming anti-pattern . It refers to using acomputer language 'serror handling structures to perform normal program logic, likecontrol flow . The term comes from combiningexception handling with the word expect: In other words, expection handling is catching occurrences that you "expect" to happen.Examples
The "reference implementation" of expection handling is blindly stepping through a collection, and catching an error when you go beyond the bounds of that collection.
This anti-pattern can cause a number of problems:
* Error handling is often slow, as it is meant to be triggered rarely, and favors correctness and robustness over speed.
* One cannot be sure that the exception that occurs is the one predicted, and is not caused by other code, such as an error within the "displayProductInfo" subroutine above. This can lead to subtlelogic error s.Another example of expection handling would be using an exception to signal that an operation completed successfully:
In this case, any code using the
saveData
function will be forced to deal not only with any input-output problem signaled byIOException
, but also with the "error" signaled bySuccessException
, which is, however, supposed to be part of the program's normal operation. Exceptions are only meant to signal about abnormal situations, and should not be used to merely pass information.When expection handling is not an anti-pattern
In
unit testing , it becomes necessary to verify that the code correctly throws exceptions in situations when it is supposed to. For example, when testing a collection, the tests can verify that the class indeed throws anIndexOutOfBoundsException
when an invalid index is passed.JUnit version 4 includes support for expection handling via theexpected
parameter of the@Test
annotation, which considers the test failed if the exception specified in it is "not" thrown. Using JUnit 4, a simple test forArrayList
's behavior out of bounds can be written like this:Before JUnit added support for the
expected
notation, the code had to be written as follows:
Wikimedia Foundation. 2010.