News for hackers. Stuff that matters.
Re:You’re better off using Exceptions by waynecochran on Monday February 03, 2020 @11:32AM (#22225721)
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.

Re:You’re better off using Exceptions by quietbritishjim on Monday February 03, 2020 @12:20PM (#22226319)
That 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".
Re:You’re better off using Exceptions by waynecochran on Monday February 03, 2020 @01:43PM (#22227426)
Yes... RAII is handy, but it doesn’t save you from checking EOF logic in my example.
Re:You’re better off using Exceptions by safety-second on Monday February 03, 2020 @02:41PM (#22228106)
You 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.
Re:You’re better off using Exceptions by quietbritishjim on Monday February 03, 2020 @05:49PM (#22230231)
Exceptions 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.
Re:You’re better off using Exceptions by gwbas1c on Monday February 03, 2020 @02:47PM (#22228174)
> 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.

Re:You’re better off using Exceptions by waynecochran on Monday February 03, 2020 @05:06PM (#22229780)
Simply count bytes as they are read. In the exception handler check to see if the count matches the expected value. Clean.