Quote:
|
Originally Posted by MBirchmeier
The problem is (especially when learning to use exceptions) there's a tendancy to overuse them, say in the example of opening a file, the following shouldn't be exceptions:
The file not existing
The file being locked
The file not being the format expected
Not being able to write to the file
|
Again, I disagree. When one writes some code to open a file, the usual expected result is that the file is opened correctly. Any other result should be cause an exception.
Now, if one were doing work with threads, then one might expect files to be found locked regularly, and because it is expected, one would probably have some function to check whether the file is locked rather than handle it via an exception. Likewise, if one wishes to write to a file that may not yet exist, then one may specify an option to create the file, if it doesn't already exist, rather than to handle it with exceptions.
But this only applies when the difficulty is a common and expected occurance. When the difficulty is unexpected, such as with your third example ("The file not being the format expected"), then you should certainly use an exception. Indeed, I'd go so far as to say it's bad practise not to use one.
The other factor to consider is the handling of unexpected events. If I have an application that accesses a file, and that file turns out to be in an invalid format, then it's logical that I report said error to the user. But since my program is clean and modular, I can't pollute my document opening function with GUI specific code. Likewise, because I happen to be using a statically typed language, I can't return an error message when a document is expected.
So I either have to wrap up the document in an error handling layer, or I have to record the error in a global variable that can be polled when necessary. In short, I have to create my own exception handling routines and reinvent the wheel. And reinvent it badly, as it happens, since neither solution has all the benefits that exceptions have.
Thus, in any case where non-standard behaviour occurs, exceptions are the best way to handle it.