Why We Use Exceptions

Language constructs such as events and signals are part of a normal program flow. Exceptions, by contrast, indicate that something has gone wrong while executing the program, such as a function called with wrong parameters so that the result cannot be calculated. For example, suppose we have a function that divides two numbers and accepts them as parameters. Naturally, division by zero is not possible, and should such a function receive an instruction to divide by zero it would have no idea what to do. So a seemingly simple function becomes rather complicated; it has to check whether it can divide the two numbers it is given and also return two values instead of one. One value is to indicate whether the operation completed successfully, and the other holds the actual result. Alternatively, it could return either a number if the operation was successful or a null object otherwise. In either case, the code that called this function now has to be able handle both numbers and null objects as a result, rendering simple arithmetic constructs into more complicated if ... else logic flows.

This is where exceptions come in. Instead of returning a special code that indicates the error, functions that cannot complete their normal operation will simply raise an exception. At the moment when an exception is raised, the program execution stops and the Java environment proceeds with the exception-handling procedure. Exceptions can be "caught" by the application. Going back to the division example, the whole calculation code can be wrapped in Java's try ... catch construct. Then, regardless of the point at which the code failed, and the specific function (such as division), the code would catch any arithmetical exceptions and would know than the calculation couldn't have been completed.

Was this article helpful?

0 0

Post a comment