Exceptions are a way of communicating an exception or error condition from a method to the caller of the method. Exceptions are favored over the older technique of returning a status code from a method, such as 0 for success and 1 for error, because exceptions can't be ignored by the calling code. Without exceptions, it's easy to write code that assumes every operation is successful. When an operation doesn't end in success, the error can show up in subsequent operations, and therefore be harder to diagnose. In most implementations, throwing exceptions is a relatively expensive operation. Therefore, exceptions should be used to communicate truly exceptional conditions rather than conditions that may occur under the normal execution of a program. The benefit of using exceptions usually increases with the size of the application. Exceptions require the developer to define the success and error conditions of methods and require the calling code to handle both possibilities. Code therefore can have fewer bugs and be clearer and more robust than code that uses another error reporting mechanism or ignores error conditions altogether. Additionally, exceptions help with the principle of failing early. In general, it's better to fail (raise an exception) at the first sign of trouble when the cause of the failure is well-known. Otherwise errors might cascade to other parts of a program where they are harder to diagnose. |
Contents
|
