6 ms·
Exception != Error Old Ada programmer here. Example of reading bytes from a file... just keep reading bytes and don’t include logic for checking for EOF. Let t
by waynecochran 7y ago
Exception != Error
Old Ada programmer here. Example of reading bytes from a file... just keep reading bytes and don’t include logic for checking for EOF. Let the exception handler catch it where the file will be closed. Clean separation of code.
In Ada, every bock can have exception handlers at the bottom. No need for “try” syntax. Very clean.
- quietbritishjim 7y agoThat is like C++ destructors, which are called deterministically when they go out of scope (again with no "try" syntax). They can unlock mutexes, close files, etc. But unlike what you describe, there is no need to put anything at the end of the function: instead, the fact that you have instantiated an object already guarantees that its destructor will be called later. This is called RAII, short for "resource acquisition is initialisation".
- waynecochran 7y agoYes... RAII is handy, but it doesn’t save you from checking EOF logic in my example.
- safety-second 7y agoYou could use a File class that throws on EOF, but that would be a really bad idea for C++ since throw/catch are very expensive.
- quietbritishjim 7y agoExceptions are expensive compared to a simple function call, but I imagine they're cheap compared to operations that read from disk. Certainly one exception per file close is not going to hurt.
- gwbas1c 7y ago> don’t include logic for checking for EOF. Let the exception handler catch it where the file will be closed What happens if the file is smaller than you anticipate? That's why exceptions aren't used for flow control.
- waynecochran 7y agoSimply count bytes as they are read. In the exception handler check to see if the count matches the expected value. Clean.