This feels more like a "Oh I have exceptions, I better use them" situation. And his solution is to pick a language without exceptions so he doesn't have to use them. It's all very odd.
[1] I remember reading a MIME encoding library years ago. There was a point where the code would detect an error but if the error was at the end it would just drop that part and write in the last couple of bytes. In this situation, most clients won't care that this is happening but what about those that do? Since this code signalled error by returning NULL there was no way to signal "saw an error, but fixed it". In Common Lisp, signal could have been used for clients that would want to report on this.
"C++ exceptions just didn't fill the bill. They are great for guaranteeing that program doesn't fail — just wrap the main function in try/catch block and you can handle all the errors in a single place."
That's not C++'s fault, or Exceptions' fault in general: that's your fault for using an extremely useful and versatile language construct completely incorrectly.
If a high-level language is bad because it offers you more functionality and features than you know how to use, then sure, maybe you shouldn't be using a high-level language. But this argument is almost like decrying being rich because you don't know how to use your money wisely; trust me, it's still better to have money, and you shouldn't throw away your high-level life just because it's "simpler to be poor."
If your goal is to do high-level complex things, it's better to use a high-level language. If your goal is to do low-level pedal-to-the-metal things, then it's better to use a low-level language. But the simple fact that a high-level language is high-level is not a valid criticism. Not of the language, anyway.
Yeah, this kind of statement always scares me. In my experience people proposing it tend to 'handle it' by simply ignoring it happened. As if by simply catching and not crashing you have averted disaster. Nevermind that very little, if any, code is truly exception safe. That exception just tore through N frames of code interrupting each one at who knows what step and who knows what kind of state the object is now in. If you were lucky they were at least using RAII objects to ensure they haven't leaked things, but that is only half the battle. Unless they are using some kind of transactional approach to mutating their own instance state you likely have an object in a 'half-transitioned' state, which will likley violate various invariants the original author assumed (incorrectly) would always hold. Continuing in C++ (or really any language) after swallowing an exception 'around main' is a supremely bad idea, unless you like heisenbugs or getting pwned.
>you shouldn't throw away your high-level life just because it's "simpler to be poor."
It made me think of people that have won the lottery and after they've finally blown through all their winnings many concur that: it's "simpler to be poor."
try {
...
int rc = fx ();
if (rc != 0)
throw std::exception ("Error!");
...
catch (std::exception &e) {
handle_exception ();
}
Why is he throwing exceptions and catching them within the same function? His "C equivalent" is what he should've been doing in C++."C++ exceptions just didn't fill the bill. They are great for guaranteeing that program doesn't fail — just wrap the main function in try/catch block and you can handle all the errors in a single place."
This is something i learned in my very first computer science lecture not to do.
To be fair: It's what exceptions can be good for - a last barrier before a crash and a way to handle errors later. But you're absolutely right that he simply could react directly to the error. Or throw specific exceptions and react to them. His described issue has nothing to do with exceptions themselves, just with the way he thinks he has to use them.
Memory corruption? Appropriate response: fail. Logic error? Appropriate response: fail. Exception? Appropriate response? Decide if program can continue, respond.
I'd say the bigger issue is less of "exceptions" so much as "states". Adding any kind of error handling increases the number of state conditions that your program may be in, and that complexity is obscenely hard to manage. I don't think C or C++ or Java or Erlang or any other language will free you from the burden of proper software engineering.
Not only that, I don't think C++ exceptions are necessarily very good at being a 'last barrier' before a crash - they simply can't catch all the errors, because they are good at indicating conditions that might be recoverable, not catching and recovering from logic errors that would cause a crash. There are plenty of ways to hang yourself in C++ without ever throwing an exception.
Ah, Java code at my workplace.
catch(Exception e) {}Yes, and he learned not to do it also, thank you.
He makes a tongue in cheek comment about a common Exceptions abuse. Actually, in the very next sentence after than one, he explains why that is bad.
Do people on Hacker News believe that the guy doesn't know C++? He is the frigging author of one of the most useful, used, high quality C++ libs.
No, he doesn't. The very next sentence is:
"However, what's great for avoiding straightforward failures becomes a nightmare when your goal is to guarantee that no undefined behaviour happens."
It's great if your goal is to avoid straightforward failure (= crash), it's bad if your goal is to also avoid undefined behavior (= invalid program state).
Have you discovered something else on the matter?
Yes, and as a Comp Sci, and developer of 15 years, I knew it all before. It's not like the discussion got into any advanced territory.
>If you don't use exceptions in the way he described them, you don't have undefined behaviour (general big exception handling at the end vs granular error-checking, which is of course also possible with exceptions). Everything he described has nothing to do with exceptions, but with the way he uses them in the examples he showed.
Which is the ways that are relevant to his project and coding style. People on the HN thread were just quick to second-guess him without understanding the problem domain and his constraints (which were: "I want to use exceptions in X way for them to be worth to me. I won't even consider the Y way --what some in the HN discussion proposed-- because it's convoluted, requires far more code and maintenance and if I have to do that, I might as well do it in C".
For example, you cannot wrap each and every spot with a try/catch because this doesn't buy you anything over the C way of error checking.
Also, you cannot know what exactly occurred (at coding time, not runtime by checking the stack), unless you granulize (granuralize?) exceptions to death. But then, why not just check the error conditions/codes? And if you do so, what you get over C?
etc...
try {
foo();
catch (std::exception &e) {
handle_exception ();
}
int foo () {
int rc = fx ();
if (rc != 0)
throw std::exception ("Error!");
}When you can't count on a GC to clean up for you every function has to be carefully coded to prevent potential leaks. Browse through some of Herb Sutter's GOTW questions to get an idea of exactly how tricky this can be.
Of course the recommendation from Stroustrup & Sutter is to use the new smart pointers for everything but I think it will be a few years at least before most people can follow that advice.
Image* image = allocate_image(…);
…
deallocate_image(image);
↓
struct ImageDeleter {
void operator()(void* image) const {
deallocate_image(image);
}
};
unique_ptr<Image, ImageDeleter> image(allocate_image(…));
That certainly can’t work everywhere, but I have yet to be failed by it. std::unique_ptr<Image, void (*)(Image *)>(image, deallocate_image);scoped_ptr<Image> image(allocate_image(...));
// C
int rc = fx ();
if (rc != 0)
handle_error ();
// C++
int rc = fx ();
if (rc != 0)
throw std::exception ();
This is absurd. This is not the same thing in two different languages. These two pieces of code do two different things. One handles the error, and the other signals that there's an error that should be handled elsewhere. For an apples-to-apples comparison, let's consider both cases in each language. If this is the appropriate place to handle the error, then you handle it. It looks like this: // C
int rc = fx ();
if (rc != 0)
handle_error ();
// C++
int rc = fx ();
if (rc != 0)
handle_error ();
I.e., exactly the same. If you DON'T want to handle the error here, then you return an error code or throw an exception: // C
int rc = fx ();
if (rc != 0)
// There's no way to know where or whether this will be handled
return some_error_code;
// C++
int rc = fx ();
if (rc != 0)
// There's no way to know where or whether this will be handled
throw some_exception();
You're in the same boat in C and in C++. The error must be handled elsewhere, and nothing you do here can ensure that it will be. Exceptions have some advantages, though:1. You do not have to anticipate inconvenient collisions between error return values and valid return values.
2. If the calling function is not the appropriate place to handle the error, then no boilerplate is required in the calling function to pass the error up the stack.
3. Exceptions let you use destructors instead of explicit cleanup blocks.
4. Failure to write error-handling code will not result in an operation proceeding in an invalid state, deceptively reporting success, or silently corrupting state. An error return value can simply be ignored. An unhandled exception will cause a cascading failure that cannot be mistaken for successful completion of an operation.
5. You can always use return values to report errors if they happen to be preferable in some cases.
P.S. The more I understand his complaints, the more I think he is just trying to get too fancy. If construction and destruction are problematic for some objects, then classes with trivial constructors and destructors give him exactly the struct-like behavior he wants, so what is wrong with that? How in the world do you get into worries about exceptions thrown from constructors and half-initialized objects (exception in the sense that any allocated-but-not-initialized struct is in a "half-initialized" state)? This is like saying knives are too dangerous to have the in the kitchen because you are in the habit of thrusting your hand blindly into the knife drawer.
In a static language like C++, this is a big disadvantage.
The process of adding an exception in Java:
1. throw TheException
2. compile
3. add "catch(TheException e)" to fix errors or "throws TheException" to signature
4. repeat 2 until no more errors
Compare to C++:
1. throw TheException
2. examine all functions to determine if they might need to handle TheException or consult intuition about program structure
3. repeat 2 until 'done'
So the real problem with exceptions in C++ is the compiler can't tell you where to look next and what you forgot about. Step 2, magically find all the places that should catch the exception, is both time consuming and error prone.
I find it strange that C++ has all kinds of strictness with types (have to cast void*, const virus, etc) but with exceptions they just throw caution to the wind.
Googling for ---java checked exceptions--- is illuminating.
Unchecked exceptions, however, mean that code that would previously always succeed may now never even be executed. Which makes it difficult to reason about the behavior of your function.
It's the same trade-off that appears in several other areas of language design. Do you force developers to write down their assumptions in the source code, so that everyone reading it knows exactly what's going on? Or do you let them keep it in their heads, so that it can change easily when the system requirements change? Dynamic vs. static typing, global variables vs. parameters, polymorphism vs. conditionals, default arguments vs. explicitly specifying parameters - it's all the same fundamental argument applied to different language constructs.
Which side your on usually ends up depending on whether you read more code or write more code. Maintenance devs always want things to be explicit, because it makes it easier for them to grok the whole codebase and make the change they need to do. Green-field innovators always want things to be implicit, because it means they have to specify less, and everything they specify tends to end up changing anyways. Sometimes the same person ends up cursing both ends of the divide depending on what they happen to be doing at the time. I do a bunch of speculative prototyping for Search Features at Google; in this role, 90% of my code never sees the light of day, and so I write it with tools like Python or JQuery that let me easily change things around and not specify too many of the details. I also do a fair bit of infrastructure work on the search stack; in this role, I write barely any code and spend the bulk of my time tracking down where an obscure piece of data is coming from and how it needs to be modified to add a new feature.
The problem as I see it is that if you advocate the alleged consensus that checked exceptions are evil then you are taking the position that there is no trade-off. Checked-exception lovers like myself acknowledge this grey area and the design challenges it presents. That is a big part of why I believe that a Java with checked exceptions is more "reality-based" than one without them, it recognizes the challenge and gives an API designer the tools to do the right thing. I want to have that hammer in my tool chest instead of banging on things with the back of my hatchet.
In Java, you can do:
public int myfunc(int a, int b) throws IOException, InvalidGoatException {}
How would you do this in C++?
yeah throw() can contain multiple types that can possibly be emitted e.g. int foo() throw(a,b,c,d) implies that foo can only throw either a/b/c/d types.
It’s the same with any feature of any language. You can choose not to use exceptions in your code, if that makes it easier for you to understand and manage, but it’s certainly not the fault of the feature in general.
Basically, it’s up to you to structure your code well. Yes, it gets bad if a potentially throwing function can be called from multiple points. The error needs to be handled at every one of those points, and probably in much the same way.
But if you see repetition, why aren’t you factoring it? And why are you calling that function from multiple unrelated locations in the first place?
I get it. I’ve used C++ for half a lifetime—it’s a hopelessly broken language. There are tons of things about it that just make me furious. But I can get stuff done in it because I’ve taken the time to understand it in depth. Don’t complain about the language or a particular feature thereof just because it’s not suited to your problem or your way of thinking.
There are other languages out there (Erlang) that are far better suited to stable zero-downtime systems than C++. There are languages (Haskell, Lisp) that help you better manage complexity than C++. Every language implementation worth its salt has C bindings, so you can write performance-critical code at a low level, while still managing the whole system in a high-level language. There are options. Explore them!