3 ms·
I think a language's standard library sets a good pattern for how to write idiomatic code in that language. C++ throws on memory allocation error, but that's a
by knorker 4y ago
I think a language's standard library sets a good pattern for how to write idiomatic code in that language.
C++ throws on memory allocation error, but that's about it. Memory allocation errors are special in all languages. Because of lazy allocation and overcommit, unless you specifically set your environment to work otherwise, your program will probably just crash when it gets its first page fault that can't be honored.
Open a file? fstream sets .is_open() (or its operator bool, so just "if (!f)")
Write fails? Sets .fail()
POSIX stuff usually return an error code, and set errno.
Modern C++ has std::optional.
But there's of course another answer to this, and that is "C++ has zero cost abstractions", meaning for example if you don't check for nullptr, then neither will the language. There's no NullPointerException because C++ just says that this is Undefined Behavior.
Oh, here's one: If you use dynamic_cast to try to downcast into the wrong type, that'll throw an exception. But first of all: don't downcast, and second of all: This is not an "unexpected input to function". This is a complete programming error and it's probably best to terminate. I.e. this is something Go style would panic about, not return an error.
Do you have more specific examples about unexpected input to a function that you would want to return an error for?
Ugh. Actually std::stoi() violates this pattern. If std::optional existed in C++11 it would probably have been used here.
- grishka 4y ago> Memory allocation errors are special in all languages. Actually no, not in Java! You can catch java.lang.OutOfMemoryError just like any other exception. If the memory pressure is high though, it's possible that another OOM would be thrown from the code that handles it.
- knorker 4y agoYou can catch std::bad_alloc in C++, too. That's not my point. Especially because destructors free immediately (not wait for GC) I would expect C++ to handle this as a language much better than Java. But when memory pressure is high you can get killed at any time. E.g. on Linux the OOM killer might decide that it's best for the system that your process dies, even if you've not done memory allocations or needed to page fault for hours. IIRC OpenBSD doesn't overcommit memory, but in my experience its system stability is much worse when memory is low.