I am using the following construct to read data from a file. Is there
a better way to do this? Currently I'll get the associated IO exception
which doesn't seem to be as elegant as it should be.
Joined: Apr 09, 2009
.....allow me to elaborate.
If I execute the code in the OP within a try block then I should certainly catch any exceptions.
Would it be proper to use the catch to proceed with 'normal' program execution?
If yes, what if some other IO exception occurs?
I've experienced this problem before, and it indicates an ill-designed way of storing data. All you need is one extra int before all objects that indicates how many objects there are. This is how most collection classes handle their serialization - first the size is written, then each element. Reading is similar: read the size back first, then read "size" elements.
Should you not know the number of elements you can use booleans between before and after each element. In short, the stream will contain this: (true, object)* false. In normal words, you get 0 or many occurrences of true followed by an object, and the last object is followed by false. Reading is then simple as well:
There is more overhead this way (one int versus n+1 booleans for n objects) but if you don't know n there is little you can do except catch exceptions, and that is nasty, especially if there is data after these objects.