5 ms·
> I like C++ exceptions as a feature In your opinion, what are situations/examples that justify the use of exceptions? I haven't used a language with exceptio
by dgellow 7y ago
> I like C++ exceptions as a feature
In your opinion, what are situations/examples that justify the use of exceptions?
I haven't used a language with exceptions since 3 years (i.e: since I switched to Go), and I haven't yet faced a situation where I felt a need for them.
Also, I started to learn C++ as a hobby a few months ago, and I have to say that I still don't understand when I should use exceptions or not, things seem fine so far by just returning some error values.
- ailideex 7y agoExceptions are ideal for happy path programming. You keep state in the stack and build your software so things get thrown away. For some types of programming this is not that important but for OLTP it is very handy. https://ninenines.eu/articles/dont-let-it-crash/ https://ninenines.eu/articles/dont-let-it-crash/ Basically this approach is handle errors if you know what to do with them, otherwise leave the error for something else. In erlang, where you have one process per transaction, and nothing handles the error, the process crashes. In C++, you could just have an exception handler around a transaction, and then when an exception reaches that point you throw away the transaction, but log that it failed, you could have exception handlers below this to try and do rollbacks etc. This is overly simplified but it gives a basic idea.
- dgellow 7y agoThanks for your answer. What is OLTP in that context? Is it https://en.wikipedia.org/wiki/Online_transaction_processing https://en.wikipedia.org/wiki/Online_transaction_processing? First time I see that acronym.
- ailideex 7y agoOLTP in this context is indeed online transaction processing. This general approach of «let it "crash"[1]» or happy path programming is what I used when I wrote OTLP systems for mobile networks which were performing financial transactions. The exception handling would allow you to write fairly complex business logic and relying on exception handling to recover to a stable state. [1]: Crashing in Erlang terms is not at all what people generally mean with crashing. It is a very unfortunate word because in part many of the problems in node.js comes from joyent not understanding what "let it crash" meant - it did not mean let the unix process crash. Erlang does one process per transaction and they are incredibly lightweight. Some details from joyent can be found here: https://www.joyent.com/node-js/production/design/errors https://www.joyent.com/node-js/production/design/errors
- humanrebar 7y ago> ...leave the error for something else... In my experience, the amount of interesting logic that "something else" does is vanishingly small. An arbitrary real-world example probably just logs or returns a string that is opaque and mostly useless to any potential error recovery mechanism. In theory one could throw a FileExistsException with semantic and accessible data like filePath, but as things get this specific, they practically become part of the API. And a leaky part at that. The top-level entities that need to handle the exception need to know, somehow, that (1) encapsulated implementation details may throw something specific and (2) what to do with the thrown events. So, practically, programs tend to catch std::exception, and pass the opaque error string on to some form of external I/O system (logs) with some minimally informative error status code (ERROR, 5XX, -1, false, null). It is interesting to perform transaction failure operations, but there is no std::transaction_aborted, std::connection_dropped, or std::resource_busy. More realistically, std::exception is caught, which could just as easily be std::bad_alloc or std::domain_error. What do you do with a domain_error? I don't know either. At any rate, the most interesting feature for transactional logic is RAII semantics, and you don't need to use exceptions to leverage those.
- saagarjha 7y agoIn my (unrequested) opinion, exceptions are useful when there are errors you don’t really want to handle during normal execution. Things like malloc failing, or open files suddenly disappearing out from under you (e.g. someone yanked a hard drive). They are errors but trying to handle every little bit of how a computer can go wrong is not really a feasible task, although you might be inclined to handle some.
- dgellow 7y agoI agree with your two examples (malloc failure and hard drive issue). > They are errors but trying to handle every little bit of how a computer can go wrong is not really a feasible task, although you might be inclined to handle some. Though, using error values, it's not that different. 1. check if the error is something that you care about 2. if not, check if it is something that you should pass back to the caller (in general that's an assert "if not null/empty"), if it is then return it 3. otherwise continue what you're doing in the current function You have the same result without a need for exception, you only handle what you care about in the current scope, or let the chain of callers decide what they want to do with the error.
- saagarjha 7y agoExceptions are basically sugar for that, since this kind of thing is done so commonly that it’s useful to have a construct for it.
- Reelin 7y agoIt's too easy to forget to check or propagate an error value (in most languages) though. Exceptions are nice because you can't forget - you either handle it somewhere in the call stack or the process is killed.
- senderista 7y agoThose sound like unrecoverable errors. Exceptions only make sense for recoverable errors, otherwise why not just call abort()?
- fwsgonzo 7y agoAs a general rule, use them when for truly exceptional situations: Running out of memory, accessing something out of bounds - things that you are checking for anyway, but you don't or don't want to use a return-value-based error handling system for. In modern C++ this is already the case. For example, every container that implements an at() function will throw an exception if the (unsigned) index is >= size. If you look at the assembly of a simple function only accessing a std:array using the [] operator, you will see that it's quite small. If you access it using at() you might see that the core function remains the same, except it now has a bounds-checking test which jumps to a huge postamble. The postamble will throw the exception. Since the CPU likes to execute instructions in sequence, we say that the happy path (which is indexing correctly) is now the fast path.
- senderista 7y agoWhy use exceptions for unrecoverable errors? The only reason would be to do proper stack unwinding, and if the proper response to an unrecoverable error is to terminate the process, I don't see the point of cleanup.
- jcelerier 7y agoyou most certainly never had to wrestle with operating systems keeping sockets open for a few minutes after a process was killed then. pleaaaase do unwind properly and release as much resources as you can.
- pingyong 7y agoWell, in the case of C++, since the standard library uses exceptions everywhere not using them is a pretty big "cut". Basically either you don't use the standard library or you write all your code in a completely different paradigm. For example, since constructors can't return error values reasonably, you would have to make them all private and use static factory functions, or similar workarounds. It's certainly possible, but much less pleasant to work with.
- dgellow 7y agoThe constructor example is an interesting one. A Go constructor is just a function such as `func NewMyObject(someParam string) (*MyObject, error)`, it is possible and not that uncommon to return an error in addition to the instantiated object, for example if there is some check on the parameter (an example I have in mind is http.NewRequest https://golang.org/pkg/net/http/#NewRequest https://golang.org/pkg/net/http/#NewRequest). How do people deal with constructor errors in the C++ world? I have never seen C++ code where the constructor call is wrapped in with an exception handler. I would guess that's done by creation an addition function "make_my_object"? But then what is its signature? Or is an exception handler used in that case?
- erik_seaberg 7y agoIf I create several objects and then one of them fails, the ones that succeeded get destructed in reverse order, and then my callers get the exception that killed me. I don't need a handler unless I know what to do about it or I'm doing something weird that doesn't work with RAII. And I can't even try to use an object that didn't properly initialize.
- dgellow 7y agoI see, that makes sense
- pingyong 7y ago>How do people deal with constructor errors in the C++ world? I have never seen C++ code where the constructor call is wrapped in with an exception handler. There are about 200 different ways to be honest, stemming from the unfortunate situation that the most common advice, "use exceptions in exceptional situations", is actively harmful. Let's take a "Connection" class for example. You'd initialize it with an IpEndpoint, or something to that effect. Some people think "well I'm writing a download script so if I can't connect the script can't continue, so that is exceptional" - so they throw an exception in the constructor and catch it somewhere in main. Other people are writing something more complicated and they think "being unable to establish a connection is normal, I'll just make a factory function for this and wrap the Connection constructor". Which leads to completely different paradigms in the same situation but with different environments - and those two decisions are both good, there are tons of decisions that aren't! This is compounded by the fact that the C++ standard library only uses 2 kinds of resources: Memory and Files. And they use different kinds of error handling. Well, memory allocation always throws (at least it's consistent here), but the iostream error handling is, uh, interesting? Streams don't throw by default, however you can enable them to throw at runtime, but they also store their error state inside. It's a mess really. Oh and also the std::logic_error exists and gets thrown by standard library functions, but a lot of advice around exceptions says that you're not supposed to use exceptions for programming errors, that should be handled by assertions. And then there are of course people who just disable exceptions. Some disable exceptions but still use the standard library and just kind of hope that everything will still work? So yeah, it's a mess. That's partly why proposals like this would help - if you can make the actual throwing of exceptions cheap, the advice of "use exceptions for exceptional situations" goes away instead becomes "use exceptions for every kind of error handling". Which would be much more consistent. And people wouldn't have an excuse to disable exceptions anymore, at least in the long run.
- epage 7y agoAs a Rust fan boy where the Error monad is used instead of exceptions, there are times where exceptions are nicer. One example is when using `map` and other functions on iterators. With exceptions, error reporting is out-of-bound. Without them, things get messier, see https://doc.rust-lang.org/stable/rust-by-example/error/iter_result.html https://doc.rust-lang.org/stable/rust-by-example/error/iter_... I've got some ideas for siphoning off the errors to make them out of bound. Will need to experiment to see how ergonomic it is.