4 ms·
>It puts error handling code far from where errors occur, and where you often have the best chance to deal with it So, you pass file name to your data access l
by azov 11y ago
>It puts error handling code far from where errors occur, and where you often have the best chance to deal with it
So, you pass file name to your data access library and the file is not there. How are you going to deal with it? Write an error to the log nobody reads and call terminate()? Create a new file and let users guess what happened to the data they expected? Or return an error code?
If you picked the last option (as most people do) - well, bingo, you've just put your error handling far from where the error occurred. The only difference with throwing an exception is that now every function up the call stack needs to check that error code till it reaches the place where you can handle it or, even more likely, till someone forgets to check or chooses to ignore it. Because, unlike Go or Rust, C++ compiler won't help you there.
Error codes don't undo I/O either.
As to "which functions can throw" - let me suggest a simple rule: every function can, unless you can prove otherwise.
Look, there are situations where it makes sense to avoid exceptions, but not for the reasons you listed. Exceptions are the least evil way to handle errors in C++. Google style guide bans them mostly for historical reasons, let's not cargo cult it.
- vardump 11y ago> So, you pass file name to your data access library and the file is not there. How are you going to deal with it? Write an error to the log nobody reads and call terminate()? Create a new file and let users guess what happened to the data they expected? Or return an error code? Perhaps return an error code. Which the caller would check and deal with the error. (Besides, I'd be passing a stream object, not a filename.) I/O is also network packets, graphics on the screen, motor movements. > P.S. As to "which functions can throw" - let me suggest a simple rule: every function can, unless you can prove otherwise. Exactly, that's the problem.
- sbmassey 11y agoHow about wrapping the return value in a templated error class that the caller has to explicitly unwrap with an error handler to be able to use?
- azov 11y agoThat will help if there is a value to return - but then it's not much better than just returning something invalid, like a NULL pointer. If the only return value is success/failure you need compiler support (1) to ensure it's not ignored. (1) There are clever hacks to mimic this behavior to some extent, but I don't even want to go there. If you really want this feature - just use a language that has it.