I am sure that as a programmers we would have definitely pondered how best to report errors. Let us consider the available options:
- Return special values indicating the occurrence of error (or)
- Throw exceptions
The first approach is the only method possible in older generation languages such as C where as exceptions are available in the newer languages such as Java, Python etc.
Exceptions are much superior mechanism for reporting errors as compared to returning status codes. Why that is so is enumerated below:
- Exceptions cannot be ignored unlike status codes - As checking for status code is not mandatory, it is very common for developers to ignore the return values of methods. This implies that the error is not reported when it occurred causing the application to fail at a later point in code thus making the debugging that much harder. Exceptions on the other hand propagate up the calling stack until a matching handler is found or is caught by the runtime in the absence of a matching handler in code usually causing the application to fail. Thus an error reported via exceptions is always reported.
- Sometimes returning status codes is not an option
- Certain constructs like constructors do not return anything, so one cannot use status codes to report errors.
- In case of operator overloading which are basically implicit method calls, it is again not possible to return status codes indicating error
- Exceptions carry context unlike status codes - When an exception is caught, the entire stack trace is made available starting from the point where it occurred.
- Exceptions can contain more descriptive error messages unlike status codes - Typically, the error messages reported via exceptions carry more information that what is possible to convey by just a error code.
- For example, in a readFile() method, if the file is not found it might return a status code say -2 indicating that the file was not found. The same error when reported via a FileNotFoundException can be coded to contain a more descriptive message such as "File /tmp/abc.txt not found"
- Unlike exceptions, checking for errors clutters up the business logic - As multiple error code returns are possible, the error checking logic becomes tedious and often overshadows the actual business logic. Exceptions on the other hand result in much cleaner code as error handling can be kept separate from the business logic.
Caveats
Having said the above, there are cases where it is not appropriate to use exceptions
- Exceptions should NOT be used as part of normal flow - Do not use exceptions to report any of the possible normal states of an operation. In such scenarios, convey the status of the operation by returning appropriate status code. Exception handling is expensive and should only be used to handle exceptional/abnormal conditions
References
No comments:
Post a Comment