News for hackers. Stuff that matters.
Re:Why should I have written ZeroMQ in C, not C++ by evincarofautumn on Thursday May 10, 2012 @10:45AM (#3953760)
This is absurd. Exceptions are just generalised returns. You can use them well and benefit from them, or use them poorly and make the stuff of nightmares.

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!

Re:Why should I have written ZeroMQ in C, not C++ by wvenable on Thursday May 10, 2012 @11:46AM (#3954121)
I agree the whole rant about exceptions just seems wrong -- if you've got a state that you can handle right there in the function itself then it's not an exception. You just deal with it. The C code and the C++ code would be equivalent.

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.

Re:Why should I have written ZeroMQ in C, not C++ by danssig on Friday May 11, 2012 @08:01AM (#3958775)
Or in Common Lisp you would be able to "signal" a condition and then handle the situation. Signal will just do nothing unless some higher level code has an explicit handler for it [1].

[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.

Re:Why should I have written ZeroMQ in C, not C++ by calinet6 on Thursday May 10, 2012 @01:41PM (#3954815)
Bingo. When I read 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.

Re:Why should I have written ZeroMQ in C, not C++ by ryanmolden on Thursday May 10, 2012 @06:52PM (#3956586)
>just wrap the main function in try/catch block and you can handle all the errors in a single place.

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.

Re:Why should I have written ZeroMQ in C, not C++ by felipemnoa on Thursday May 10, 2012 @06:48PM (#3956565)
I agree with your entire post. This part made me laugh though:

>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."

Re:Why should I have written ZeroMQ in C, not C++ by mccoyst on Thursday May 10, 2012 @11:06AM (#3953873)
One of his first examples is additionally absurd and is either the flimsiest of strawmen or he simply doesn't understand when exceptions should be used:

    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++.
Re:Why should I have written ZeroMQ in C, not C++ by onli on Thursday May 10, 2012 @11:47AM (#3954127)
He states how he understood exceptions:

"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.

Re:Why should I have written ZeroMQ in C, not C++ by figglesonrails on Thursday May 10, 2012 @01:06PM (#3954584)
Exceptions indicate //exceptional conditions//, i.e. conditions other than the intended state transitions of the program. They aren't a guard against crashing, they are a mechanism for formalizing error states in the program.

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.

Re:Why should I have written ZeroMQ in C, not C++ by cobrausn on Thursday May 10, 2012 @12:52PM (#3954484)
Though we probably learned this is not the way to use them, I have seen numerous real-world examples where this was the case.

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.

Re:Why should I have written ZeroMQ in C, not C++ by figglesonrails on Thursday May 10, 2012 @01:07PM (#3954598)
"Though we probably learned this is not the way to use them, I have seen numerous real-world examples where this was the case."

Ah, Java code at my workplace.

   catch(Exception e) {}
Re:Why should I have written ZeroMQ in C, not C++ by LoneWolf on Thursday May 10, 2012 @05:05PM (#3956022)
I believe you mean catch(Throwable t) {}
Re:Why should I have written ZeroMQ in C, not C++ by batista on Friday May 11, 2012 @03:34AM (#3958144)
>He states how he understood exceptions: "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.

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.

Re:Why should I have written ZeroMQ in C, not C++ by onli on Friday May 11, 2012 @05:53AM (#3958445)
>Actually, in the very next sentence after than one, he explains why that is bad.

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."

Re:Why should I have written ZeroMQ in C, not C++ by batista on Friday May 11, 2012 @01:07PM (#3960191)
And that's it, there's nothing more to it.

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?

Re:Why should I have written ZeroMQ in C, not C++ by onli on Friday May 11, 2012 @05:44PM (#3961581)
Of course there is. Have you actually read that discussion here? 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.
Re:Why should I have written ZeroMQ in C, not C++ by batista on Saturday May 12, 2012 @05:30AM (#3963339)
>Of course there is. Have you actually read that discussion here?

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...

Re:Why should I have written ZeroMQ in C, not C++ by rocha on Thursday May 10, 2012 @12:58PM (#3954521)
I agree, it was disconcerting to me as well. I read again and now I think that he is putting the throw there to exemplify that fx() can throw an exception.
Re:Why should I have written ZeroMQ in C, not C++ by politician on Thursday May 10, 2012 @03:37PM (#3955507)
An ellipsis means something unimportant has been elided. For example,

  try {
      foo();
  catch (std::exception &e) {
      handle_exception ();
  }

  int foo () {
      int rc = fx ();
      if (rc != 0)
      throw std::exception ("Error!");
  }
Re:Why should I have written ZeroMQ in C, not C++ by cageface on Thursday May 10, 2012 @11:17AM (#3953939)
The combination of manual memory management and exceptions is particularly nasty.

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.

Re:Why should I have written ZeroMQ in C, not C++ by evincarofautumn on Thursday May 10, 2012 @11:24AM (#3953983)
Idiomatic C++ does not rely on manual memory management—it relies on deterministic memory management. Use unique_ptr, or shared_ptr when it makes sense (hint: it rarely does).
Re:Why should I have written ZeroMQ in C, not C++ by cageface on Thursday May 10, 2012 @11:28AM (#3953999)
In theory you have every single leakable resource wrapped up in a RAII container or a smart pointer. In reality you're almost always dealing with raw pointers coming from a lower level C API or old C++ code or some kind of object handle you haven't wrapped yet.

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.

Re:Why should I have written ZeroMQ in C, not C++ by evincarofautumn on Thursday May 10, 2012 @12:13PM (#3954259)
Typically what I do in that situation is lightly wrap the API. For instance:

    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.
Re:Why should I have written ZeroMQ in C, not C++ by jmq on Friday May 11, 2012 @12:31AM (#3957654)
You can reduce verbosity of the code by passing destructor function directly to unique_ptr constructor:

    std::unique_ptr<Image, void (*)(Image *)>(image, deallocate_image);
Re:Why should I have written ZeroMQ in C, not C++ by evincarofautumn on Friday May 11, 2012 @12:40PM (#3960065)
Cool, thanks for the tip. I meant to offer an example for the general case.
Re:Why should I have written ZeroMQ in C, not C++ by jongraehl on Thursday May 10, 2012 @07:18PM (#3956672)
People who don't do this are just asking for it.
Re:Why should I have written ZeroMQ in C, not C++ by malkia on Thursday May 10, 2012 @11:27PM (#3957460)
That's a lot of boilerplate code. Okay there are macros to wrap such things, but I guess it's things like this that would make the future reader of the code puzzled.
Re:Why should I have written ZeroMQ in C, not C++ by cbsmith on Friday May 11, 2012 @05:17AM (#3958359)
jmq & basman provide examples of how to do it succinctly.
Re:Why should I have written ZeroMQ in C, not C++ by basman on Thursday May 10, 2012 @11:49PM (#3957544)
Or, perhaps easier:

scoped_ptr<Image> image(allocate_image(...));

Re:Why should I have written ZeroMQ in C, not C++ by ajross on Thursday May 10, 2012 @11:35AM (#3954051)
Sure. And using deep-thrown (i.e. thrown across module/library boundaries -- often exceptions are local tricks used within tightly coupled code) exceptions in an application where you're dealing with such pointers would be bad design.
Re:Why should I have written ZeroMQ in C, not C++ by dkarl on Thursday May 10, 2012 @07:49PM (#3956792)
Agreed. His examples are nonsensical, in almost every case comparing handling an error in C with signalling an error in C++. To see what I'm talking about, here's his first comparison:

    // 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.

Re:Why should I have written ZeroMQ in C, not C++ by evincarofautumn on Thursday May 10, 2012 @09:50PM (#3957161)
Superbly put. I cannot upvote this enough.
Re:Why should I have written ZeroMQ in C, not C++ by Blunt on Thursday May 10, 2012 @11:49PM (#3957542)
I second your Superbly put. I cannot upvote this enough too. I've been doing C and C++ for over 17 years from embedded up to CRUD accounting type apps.... Spot on my friend, spot on!
Re:Why should I have written ZeroMQ in C, not C++ by pjmlp on Friday May 11, 2012 @12:36PM (#3960036)
Well put.
Re:Why should I have written ZeroMQ in C, not C++ by Peaker on Thursday May 10, 2012 @05:51PM (#3956294)
Returns are statically typed. Exceptions are not.

In a static language like C++, this is a big disadvantage.

Re:Why should I have written ZeroMQ in C, not C++ by malkia on Thursday May 10, 2012 @03:25PM (#3955442)
It's not absurd. Just the fact that C++ exceptions were used, would make this code not portable - not being able to run on some very popular devices.
Re:Why should I have written ZeroMQ in C, not C++ by 0xABADC0DA on Thursday May 10, 2012 @02:34PM (#3955154)
Checked exceptions are great, but unchecked exceptions are a huge disaster only mitigated by failsafe features such as RAII or garbage collection with finalizers. Sometimes like in highly dynamic languages the failsafes are enough that it's ok to just use unchecked exceptions, but in a language like C++ you really can't afford to make mistakes in the first place.

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.

Re:Why should I have written ZeroMQ in C, not C++ by MatthewPhillips on Thursday May 10, 2012 @02:56PM (#3955259)
Java is the only language that I can think of that gets exceptions right, in that it forces you to acknowledge them every step in the chain and choose whether you're going to catch them or throw them upwards.
Re:Why should I have written ZeroMQ in C, not C++ by SeanLuke on Thursday May 10, 2012 @03:41PM (#3955538)
Strange. It seems to me that the consensus in the Java community is that checked examples were among the worst misfeatures of the language.

Googling for ---java checked exceptions--- is illuminating.

Re:Why should I have written ZeroMQ in C, not C++ by JamisonM on Thursday May 10, 2012 @05:53PM (#3956310)
It is strange that the consensus in the Java community sort of ended up being against checked exceptions. I for one think that this consensus is completely wrong and I suspect that what looks like a consensus is just a bunch of very loud people shouting down everyone else (and to me not making very compelling arguments). Elliotte Rusty Harold's brief post on this pretty much nails it for me: http://cafe.elharo.com/blogroll/voting-for-checked-exception...
Re:Why should I have written ZeroMQ in C, not C++ by nostrademons on Friday May 11, 2012 @12:06AM (#3957583)
The problem is that it's a trade-off - it's not a case of one side being right or wrong. Checked exceptions introduce API fragility: when the implementation of a method changes in a seemingly inconsequential way (it may now throw an error), then all it's callers and all their callers, transitively need to have their signatures edited. What should be a simple matter between just the leaf method and the top-level now has to involve all the code between them, which may not even be in code you authored or controlled.

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.

Re:Why should I have written ZeroMQ in C, not C++ by JamisonM on Friday May 11, 2012 @02:19AM (#3957974)
It is a trade-off, on that I agree with you and I do understand that checked exceptions do tend to propagate implementation-level details up where that might be undesirable. I also agree that in green-field situations it can be awkward figuring out what to do with an IOException that you suspect will not exist in a few hours.

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.

Re:Why should I have written ZeroMQ in C, not C++ by MatthewPhillips on Thursday May 10, 2012 @03:52PM (#3955616)
That's interesting. I'm not a day to day Java programmer so my perspective is different from the Java community's. I have ran into problems numerous times in other languages where an exception isn't discovered until runtime in production because there's simply no way of knowing whether a library's function might throw an exception or not. The workaround is to be overprotective. I've always envied that Java devs know what to expect from every function they call
Re:Why should I have written ZeroMQ in C, not C++ by Anderkent on Thursday May 10, 2012 @07:02PM (#3956615)
Your java library might still throw unchecked exceptions, so you have to be as careful as if all exceptions were unchecked.
Re:Why should I have written ZeroMQ in C, not C++ by evincarofautumn on Thursday May 10, 2012 @03:05PM (#3955315)
Haskell does this also, and its type system is much more expressive than Java’s, enough so that exceptions are not (exclusively) a built-in language feature.
Re:Why should I have written ZeroMQ in C, not C++ by aidenn0 on Thursday May 10, 2012 @02:57PM (#3955266)
Read up on exception specifiers in C++ and reconsider this comment.
Re:Why should I have written ZeroMQ in C, not C++ by davedx on Thursday May 10, 2012 @03:05PM (#3955319)
I just did; what I couldn't figure out, was is there a way to specify multiple different exception types in your C++ throw()?

In Java, you can do:

public int myfunc(int a, int b) throws IOException, InvalidGoatException {}

How would you do this in C++?

Re:Why should I have written ZeroMQ in C, not C++ by cbsmith on Friday May 11, 2012 @11:35AM (#3959723)
You can do much the same thing, only the meaning is the reverse.
Re:Why should I have written ZeroMQ in C, not C++ by signa11 on Thursday May 10, 2012 @03:10PM (#3955347)
> @davedx asks : is there a way to specify multiple different exception types in your C++ throw()?

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.

Re:Why should I have written ZeroMQ in C, not C++ by Peaker on Thursday May 10, 2012 @05:54PM (#3956312)
Except that is only enforced at runtime, and converts the exception type to unexpected_exception, which is even worse!
Re:Why should I have written ZeroMQ in C, not C++ by pubby on Thursday May 10, 2012 @05:17PM (#3956087)
Exception specifiers are deprecated and for good reason.