3 ms·
> you need to design your code to rollback any changes before it Citation needed on this one. In almost two decades I never once came across code that straight
by WesolyKubeczek 6y ago
> you need to design your code to rollback any changes before it
Citation needed on this one. In almost two decades I never once came across code that straight away required such rollbacks.
- setr 6y agoIts the natural control flow for try-catch exceptions: try it out, and if it fails, clean up and move on That cleanup phase is generally some kind of rollback, usually in the form of discarding whatever partially constructed datastructures (sometimes in the form of a savepoint and reverting, but thats rarer ime). The other type of catch handling is to just force everything into some sane default state, to avoid having to care what specifically borked
- dllthomas 6y agoI come across this all the time; usually it can be handled well with RAII or similar, in languages with the prerequisites. Consider a simple case where I am trying to receive data over a socket and write it to a file. I need to 1) open the socket, and 2) open the file. Whichever order I do these in, if the second one fails I need to be sure I clean up the former.
- WesolyKubeczek 6y agoHow can you be sure your cleanups worked? Use a protocol that can cope with a disconnect well. Write to a temporary file which either you then rename, or the OS discards if there was a failure. Trying to “clean up” manually can break things further since you don’t and can’t account for all possible reasons for a failure. A simple example: your hard drive is failing, and performing any kinds of cleanups on it will get your program stuck even further. Also, does it really matter too much for your stated purpose if you get an ENOSPC, an EPERM, or an EIO?
- dllthomas 6y agoYou're over-complicating it. The cleanup I was describing is freeing resources that had been allocated to the process before the error. Sure, in a sufficiently crazy situation, close() might not actually close the file descriptor - maybe I've somehow trampled on the memory associated with the function (having worked around any kind of W^X), or maybe the operating system is just seriously fucked - but it seems crazy to expect that on the basis of failing to open a file. You should still close the socket.