Checking for errors at every part may lead to developing ugly code. That is where exceptions come into handy. But the problem with exception is, we need to have a clear idea of when to use them. Exceptions should be reserved only for unexpected events.
For example, consider this scenario. If our code is trying to open a file for reading and that file does not exist, should we raise an exception? It depends. If the file should have been there, but we cannot find them, then it is exceptional. But imagine that we have only the filename. We don’t know where exactly the file is and we cannot find them, then an error return will be more appropriate.
Programs that use exceptions as a part of their normal processing suffer from readability and maintainability problems. These programs break encapsulation as their methods and their callers are tightly coupled via exception handling.
Use Exceptions for Exceptional Problems
- summary of When to use Exceptions, from The Pragmatic Programmer: from Journeyman to Master
For example, consider this scenario. If our code is trying to open a file for reading and that file does not exist, should we raise an exception? It depends. If the file should have been there, but we cannot find them, then it is exceptional. But imagine that we have only the filename. We don’t know where exactly the file is and we cannot find them, then an error return will be more appropriate.
Programs that use exceptions as a part of their normal processing suffer from readability and maintainability problems. These programs break encapsulation as their methods and their callers are tightly coupled via exception handling.
Use Exceptions for Exceptional Problems
- summary of When to use Exceptions, from The Pragmatic Programmer: from Journeyman to Master
No comments:
Post a Comment