Slashdot Mirror


The Scourge of Error Handling

CowboyRobot writes "Dr. Dobb's has an editorial on the problem of using return values and exceptions to handle errors. Quoting: 'But return values, even in the refined form found in Go, have a drawback that we've become so used to we tend to see past it: Code is cluttered with error-checking routines. Exceptions here provide greater readability: Within a single try block, I can see the various steps clearly, and skip over the various exception remedies in the catch statements. The error-handling clutter is in part moved to the end of the code thread. But even in exception-based languages there is still a lot of code that tests returned values to determine whether to carry on or go down some error-handling path. In this regard, I have long felt that language designers have been remarkably unimaginative. How can it be that after 60+ years of language development, errors are handled by only two comparatively verbose and crude options, return values or exceptions? I've long felt we needed a third option.'"

32 of 536 comments (clear)

  1. The third option by Anonymous Coward · · Score: 5, Funny

    Ignoring the error completely, data integrity or planned functioning be damned.

    1. Re:The third option by Yetihehe · · Score: 4, Interesting

      That's the philosophy of erlang, "Let it crash". Apparently this leads to some of the most reliable systems. http://www.erlang.org/download/armstrong_thesis_2003.pdf
      Apparently OP didn't heard about it, because this is the third way.

      --
      Extreme Programming - Redundant Array of Inexpensive Developers
    2. Re:The third option by pla · · Score: 4, Insightful

      You'd never do this on purpose, but its rather easy to accomplish in practice.

      You have too much faith in humanity, friend!

      I hate hate hate the exception-handling model of dealing with errors, because in practice, I've seen very, very little code that actually handles the error. People either:
      1) Use far too coarse grained a "try" (as in, on the entire function), giving almost no possibility of knowing what actually happened or how to recover,
      2) Use the "catch" just to tell the user "golly, it broke, try again later" rather than accidentally revealing the ugly (but meaningful) exception text,
      3) Assume nothing in the "try" could actually fail and only do it to satisfy their company's code auditors, so the catch does... nothing, or
      4) (My "favorite") - copy the entire body of the "try" into the "catch" and blindly do it again!

      When used correctly, exception handling doesn't make your code cleaner, it reduces to a slightly more verbose way of checking return values. You should, if you want any hope of really dealing with the error, wrap every call in its own try/catch. I have not ever seen that done (and honestly, I can't claim I do it as religiously as I should either - I tend to trust my own code (big mistake), and only do that for external calls).


      Then again, how do you handle the system volume suddenly vanishing out from under you? So, perhaps the coarse-grained "golly, it broke, try again later" folks have the right idea. ;)

    3. Re:The third option by Nerdfest · · Score: 5, Interesting

      I've gotten to prefer using runtime exceptions with a general policy of "Throw as early as possible, catch as late as possible". Only catch if you can do something about it. It works very well, and keeps the code very clean.

    4. Re:The third option by Anonymous Coward · · Score: 5, Informative

      Sounds to me like you actually hate abusive exception handling. Exceptions that are in relevant places and handle the errors in meaningful ways are good. I've seen lots of code that actually handles the error, but then I work with competent people (and yes, that is a lovely thing).

      Exception handling can make code cleaner. I'd much rather see a nice exception than return value checking as I can instantly see what kind of error is expected and what should happen if it occurs.

      Please don't dismiss a step forward from return value checking just because you're unfortunate enough to have never worked with anyone who uses it properly.

    5. Re:The third option by Simply+Curious · · Score: 4, Insightful

      I would say that it is much less verbose in the case where errors need to be propagated upward. This is exactly why not every function call has a try/catch around it. Suppose I am writing a function that accepts a filename, interprets the text in the file, and then returns some modified version of the text. With error codes, I would need to explicitly check that open_file has returned a valid file handler. I can't do anything without a valid file, so I then need to propagate the error upward. On the other hand, with exceptions, I could simply not catch that exception from open_file. I can't do anything to recover, so I should let the exception propagate upward to wherever called me, and then let them deal with it.

    6. Re:The third option by mrvan · · Score: 5, Insightful

      I think you are focussing too much on java-style compiler-forced error handling. To me, the essence of try/catch error handling is that you only catch errors if you can deal with them. If you can't (the majority of cases), let is escalate, all the way up to the user (or a log file) if needed. I think there are three sane ways of using a try/catch: (1) to actually deal with the error (this is by far the rarest), (2) mainly in loops of more-or-less independeny actions: to log the error, reset state, and continue working, and (3) at the top level, to log the error and display something less meaningful but less scary to the end user.

      I think it is a bad design decision to impose static checking on declared 'throws' statements, because that forces routines to catch stuff that they can't handle, or declare a meaningless list of everything every called routine could ever throw. In essence, it couples the signalling and handling again that exceptions were supposed to decouple.

      Another nicety of exceptions compared to return values is that the semanitcs of "something went wrong" is clear. This makes it possible to e.g. have a wrapper function that begins a transaction and commits or rollbacks it depending on the outcome (e.g. https://docs.djangoproject.com/en/dev/topics/db/transactions/?from=olddocs#django.db.transaction.commit_on_success)

    7. Re:The third option by Capitaine · · Score: 5, Interesting

      My work implies writing aeronautical software specifications. In order to facilitate FAA/EASA certification of the system, we are required to stick to the KISS principle. Data validity checks are done almost everywhere, but we are asked to design the logics so that they do not need to use these data validity statuses. Degraded mode is done through the use of failsafe values. The consumer of a data do not need to know the status of the producer. The whole system is designed so that it works and is robust with minimal use of alternate logics.

      This principle works well with dataflow oriented program and might be adaptable to other domains.

    8. Re:The third option by Sarten-X · · Score: 4, Insightful

      If you're actually seeing #4 in practice, your coworkers need a nice bit of physical re-education.

      Each situation you describe has perfectly valid circumstances:

      1) Using a "try" on the whole function is suitable on functions where a particular caught exception can only mean one thing. If you're catching a FileNotFound exception, it means the file's missing. It doesn't matter that the error happened while opening the file, or at the first read. The exceptional situation is that the file can't be found. Exactly which call had the exception doesn't matter beyond debugging (for which there's usually extra information in the exception, such as line numbers).

      2) Revealing ugly text isn't user-friendly. Rather, it shows that the programmer has no idea what's going on and is putting the burden of debugging on the user. Ideally, the exception handler will first take steps to remedy the situation on its own (config file not found? Use sane defaults and save them for next time!), then log the exception somewhere with only the meaningful parts (such as a module name, line number, and a selection of parameters). Nobody really needs to know the whole stack trace up to main().

      3) Sometimes, an empty catch routine is fine, and if it isn't fine a good code audit should notice this anyway. Some errors can be safely discarded, but the code should reflect that they are being willfully ignored, rather than just ignored out of ignorance.

      4) Despite my glib comment earlier, there are also cases where blindly retrying a step is the cleanest solution. One example I've seen recently is where a database connection would reveal a timed-out disconnection only upon actually executing statements. The straightforward solution was that if the first statement failed due to a timeout, the connection (which was now in an error state) would be checked again, reconnected, and the statement would be retried.

      You should, if you want any hope of really dealing with the error, wrap every call in its own try/catch. I have not ever seen that done...

      ...because it's a silly idea. Now you're just using exceptions as special return values. Exceptions are not supposed to mean "something went wrong here". They should mean "there's a situation that is so unexpected that I don't know how to handle". It's a different paradigm entirely. The idea is that rather than writing your program to anticipate every possible error (as the mathematicians so loved), the program should instead follow a more practical "hope for the best, plan for the worst" design. Rather than worrying about exactly which byte of a file couldn't be read, the program should just understand that something's wrong with the file, and its contents can't really be trusted.

      Then again, how do you handle the system volume suddenly vanishing out from under you? So, perhaps the coarse-grained "golly, it broke, try again later" folks have the right idea. ;)

      If your program is supposed to run on transient resources (like, for instance, a cluster that has a weak master controller running your program, and the bulk of its processors scheduled to run computation), this should be expected. Perhaps a "system vanished" exception can be raised to signal that in-process calculations should be restarted the next time the system appears, and that previous calculations should be saved in case everything else disappears, too.

      Or in other words, it broke and you should prepare to try again later. :)

      --
      You do not have a moral or legal right to do absolutely anything you want.
    9. Re:The third option by SplashMyBandit · · Score: 5, Interesting

      In Java you probably wouldn't do as you say. You would 'chain the exception; so that the original exception information is preserved even though you are transforming the exception type (eg. from a checked exception thrown from a library to an unchecked exception you don't have to declare throws clauses for). The code becomes:

      try {
      // Do something here that may throw an exception (which is 'checked').
      // eg. throw Exception();
      } catch (Throwable th) {
      throw new RuntimeException("A problem occurred when launching the SS-18 because the launch authorization code was invalid. The launch authorization code had a value of " + authCode, th);
      } finally {
      // Do any clean-up.
      }

      There are two import things to note in this contrived example:

      • * The use of the chained exception. When the exception type is transformed by the creation of the new exception we include the old exception in the constructor. That way the 'chain' of exceptions can be viewed and the original cause of the exception found. That will help you fix this issue.
      • * A message that tries to describe the exact decision used to throw the exception and the values of any contributing variables or boundary values. It is critical this information is recorded at the point of throwing because in a massively multithreaded system with millions of transactions you can't reproduce the same conditions exactly in your debugger. The only information you have is what you put in your log, and you must include all relevant information in that log. Otherwise you will not have enough data to diagnose the decision the program made to throw, and won't have enough info to fix the problem.

      Checked exceptions are valuable in Java. Those that are against them don't understand that they are very useful for certain classes of problems - systems that have to be reliable. The mistake the Java designers made was that they made the library throw checked exceptions rather than unchecked ones. If they had used unchecked exceptions everywhere (while still supporting checked exceptions for systems that need to force reliable operation under error conditions) then many of the gripes people have when encountering Java would be eliminated. Plus, programmer productively would increase because we wouldn't have to wrap and chain the checked exceptions produced by library calls all over the place. C# kinda gets it right in the fact the libraries don't have/use checked exceptions, but it lacks the option of using checked exceptions in critical systems. So neither Java nor C# have it perfect, IMHO.

      If you are a Java developer writing libraries intended for re-use by others then you should ensure your library never throws a checked exception to the caller. Only libraries for critical systems should do this. Unless you are working on nuclear plant control, avionics, medical devices, weapons systems or interplanetary probes then your system probably doesn't need to expose checked exceptions.

      The way you structure, handle and report exceptions is mundane, but is absolutely crucial for writing reliable and easily maintained software. Most programmers are sloppy about this, or consider it as unimportant as good documentation, but that is what makes then bad programmers (if you ever have to use or maintain their software).

      I hope this helps some developers out there understand how to use chained exceptions. The chaining *preserves information* about the cause of a failure. The adding sensible messages and program state is also about *preserving information* about the failure at the point of throw. Loss of information is what you are battling here, since once you lose/throw away information it is a huge effort to reconstruct it later. Avoiding loss of information is worth keeping that in mind as you develop, so you avoid doing it. Example: the built in NullPointerException being the worst example of providing zero additional information about what was null, a problem if you have multiple chained method calls on a single line. Don't write code like the Java code that raises NullPointerException.

    10. Re:The third option by west · · Score: 5, Funny

      I have not ever seen that done

      I have. The coder handled every possible exception intelligently, handled the possible exceptions in the exception handlers, handled the possible exceptions in the exception exception handlers, etc. It was phenomenal. His code could practically handle a CPU burning out at the same time as the primary disk had been hit by lightening while the database had been accidentally converted into EBCDIC.

      Unfortunately, it was also completely unmaintainable. No human being, outside of the original programmer, could possibly grok all the conditions, sub-conditions, and contingencies. The code was also 3000 lines of error handling for about 25 lines of normal execution.

      It was my privilege to gaze upon the world's most complete error handling before I fulfilled my responsibility of burning it to the ground.

    11. Re:The third option by AmiMoJo · · Score: 4, Insightful

      What a douchbag you are. In the real world there are deadlines and never enough people on hand, so you don't have time to read every bit documentation for everything. That is perfectly acceptable as long as you are still capable of developing software that is robust and does what the customer wants.

      This is why we have testing. It is more cost effective to avoid getting bogged down in making something perfect and instead get it tested as you go, making improvements based on feedback. The only people who do it any other way are writing mission critical code that costs a fortune to develop.

      You know what? You're fired. Your products are all late, way over budget, the development team hates your anal retentive attitude, while your competitors left you in the dust.

      --
      const int one = 65536; (Silvermoon, Texture.cs)
      SJW, n: "Someone I don't like, and by the way I'm a fuckwit" - AC
  2. Third option. by Andy+Prough · · Score: 5, Funny

    I think MS already tried the blue screen.

  3. Exceptions in C++ by Anonymous Coward · · Score: 4, Insightful

    While I have seen good error handing schemes in many languages, so far, I haven't seen anything as good as C++ exceptions combined with RAII. Exceptions alone aren't that great, but if you combine it with the way constructors / destructors work and compose in C++, it ends up working really well. A lot of languages with exceptions lack RAII. Java and C# have exceptions but don't have destructors (the language equivalent is much less useful than C++) much less ones that compose.

    The only real problem is that lots of C++ code rely on return codes, no error handling at all, or poor use of exceptions and resource management. There are lots of C++ programmers who stumble on error handling code and haven't learned how to take advantage of the tools the language provides. Of course error handing logic can be quite hard, even if the language helps out a lot.

    STM is also a great way of doing error handling. Transactions (like used in databases) make error conditions much easier. But they cannot be limited to databases; transactions in the file system (Microsoft has this with NTFS) and transactions in memory data structures (STM) are very valuable.

  4. On Error Resume next by xaxa · · Score: 4, Informative

    Visual Basic had:
    On Error Resume Next

    I last typed that when I was about 13...

    The documentation shows a couple of valid uses for it.

    1. Re: On Error Resume next by xaxa · · Score: 5, Informative

      (You probably know all this, but it might be interesting to someone. One of the sysadmins at work could do with reading it...)

      I practically never write scripts for Windows machines, hence never having a genuine use for that VB feature, but on Linux (etc) there's a close-enough equivalent for getting things done; and for shell scripts the default is to continue in case of error. The -e flag to the interpreter prevents this.

      #!/bin/sh
      cd /put/archives/here
      tar cjvf archive-$(date +%Y%m%d).tar.bz2 /files/to/archive/*
      rm -f /files/to/archive/*
      echo "files archived in archive-$(date +%Y%m%d).tar.bz2"

      The cd failing (network down? Disc had errors and wasn't mounted? someone moved the directory?) and the tar failing (filesystem suddenly read-only?) won't stop the rm happening, but "#!/bin/sh -e" would.

      (Alternatively, tar has a --remove-files option, which would prevent removing a file created since tar was executed, but you could still end up with the archive being put in the wrong place.)

      You can let a command fail by using ||, for example:

      #!/bin/sh -e
      cd /put/archives/here
      tar cvf archive-$(date +%Y%m%d).tar /files/to/archive/* --remove-files
      xz --best archive-$(date +%Y%m%d).tar || echo "Compression failed"

  5. First problem is considering it clutter by erroneus · · Score: 5, Insightful

    It is not clutter. It is necessary. Trash cans in the home might be considered clutter too I suppose. Some people artfully conceal them within cabinets and such, but in whatever form, they are both necessary and either take up space or get in the way or both.

    It is the reality we live in. If you want to code in a language that doesn't require error handling, you might look to one of those languages we use to teach 5 year olds how to program in.

    Good code does everything needed to manage and filter input, process data accurately and deliver the output faithfully and ensuring that it was delivered well. All of this requires error checking along the way. If you leave it to the language or the OS to handle errors, your running code looks unprofessional and is likely to abort and close for unknown causes.

    I think the short of this is that if anyone sees error checking as clutter or some sort of needless burden, they need to not code and to do something else... or just grow up.

  6. Third option by wonkey_monkey · · Score: 4, Insightful

    How can it be that after 60+ years of language development, errors are handled by only two comparatively verbose and crude options, return values or exceptions? I've long felt we needed a third option.

    Maybe - and admittedly this is just a guess from my fairly ignorant viewpoint - it's a very hard problem. How can it be that after 100+ years of industrial development, we're still heavily reliant on internal combustion engines to get us around? Why have we only got people as far as the moon in 60 years of space travel? Why, after x years, have we only achieved y?

    Because that's the way it is. Is there some reason we should have the third option by now?

    --
    systemd is Roko's Basilisk.
    1. Re:Third option by epine · · Score: 4, Interesting

      Maybe - and admittedly this is just a guess from my fairly ignorant viewpoint - it's a very hard problem. How can it be that after 100+ years of industrial development, we're still heavily reliant on internal combustion engines to get us around?

      This is a good illustration of the wisdom in Thinking Fast and Slow: the people most likely to highlight what they don't know proceed to the most sensible conclusions.

      I haven't sat down in front of a keyboard to write code since 1985 without this issue foremost on my mind. In the majority of serious programs what the program does is a tiny minority of what you need to think about. Dijkstra wrote some chapters where he illustrates that some programs will actually write themselves if you adhere rigorously to what the program is allowed/not allowed to do at each step, and bear in mind that you need to progress on the variant.

      I do everything humanly possible when I write code to work within the model of tasks accomplished / not accomplished rather than the domain of everything that could possible go wrong (error codes). It's a lot harder when error codes unreliably signal transient / persistent error distinctions. I view programs as precondition graphs, where the edges are some chunk of code that tries to do something, typically a call into an API of some kind. Who cares if it reports an error? What you care about is did it establish the precondition necessary to visit edges departing the destination vertex in the dependency graph?

      Dijkstra also cautions about getting hot and bothered about order relations in terms of which edges execute in which order. In general, any edge departing a vertex with all input conditions satisfied is suitable to execute next. Because he was so interested in concurrency, he assumed that when multiple valid code blocks were viable to run that scheduling was non-deterministic. It can make a difference to program performance which blocks are executed in which order. We enter the domain of premature optimization much sooner than we suspect simply by writing our code with overdetermined linearity (few languages even have a non-deterministic "any of" control operator).

      I had a micro-controller application in which there were many variable references of the form a->b->c->d. This is hell to be strict about precondition testing.


      bool ok;
      ok = a != NULL && a->b != NULL && a->b->c;
      if (ok) {
      ok = fragile_api_call (a->b->c->d);
      if (!ok) sideband_error_info = ERR_YUCK;
      }
      if (ok) { // lather, rinse, repeat
      }

      // ...

      // end of graph, did we succeed or fail?
      if (!ok) {
      barf_out (sideband_error_info);
      }
      return ok;

      This is the fall-through do everything possible and not a thing more programming idiom. It doesn't end up highly nested, because you flatten the dependency graph. Assignments to ok often occur at deeper nesting points than where they are later tested.

      This kind of code often looks horrible, but it's incredibly easy to analyze and debug. The preconditions and post-conditions at every step are local to the action. Invariants are restored at the first possible statement. For the following piece of code, the desired invariant is that if thingX is non NULL, it points to a valid allocation block. In the entire scope of the program, this invariant is untrue only for the duration of the statement whose job is to restore the invariant.

      bool ok = true;

      void* thing1 = NULL;
      thing1 () = malloc (SIZE_MATTERS);
      ok &&= thing1 != NULL;

      void* thing2 = NULL;
      thing2 () = malloc (SIZE_MATTERS+6);
      ok &&= thing1 != NULL;

      if (ok) {
      // more logic
      }

      if (thing1 != NULL) {

  7. Too easily impressed by White+Flame · · Score: 5, Insightful

    The author commends the use of multiple return values and a side-band error value that must be checked? Gee, multiple return values have been in Lisp forever, and maybe he's not aware of this little thing called "errno"?

    Error handling is very, very tedious by nature. There are bajillions of ways that a system can go screwy, and many of these have individualized responses that we want distinguished for it to behave intelligently in response. We expect computers to become "smarter", and that means reacting intelligently to these problematic/unexpected situations. That is a lot of behavioral information to imbue into the system, all hooked into precise locations or ranges for which that response is applicable. That information is hard to compress.

  8. Re:People just doesn't get it by joe_frisch · · Score: 4, Interesting

    Software that interacts with the real world needs some way to handle errors. We have a distributed control system (MATLAB / EPICS based) that runs our accelerator (SLAC). The code needs to deal with a hardware device that is broken and has returned a nonsensical value, or does not return anything. This needs to be dealt with in some way - whether it is by throwing an exception or by checking the return from the routine that made the call. The error handling can be fairly complex, some devices are vital to operation and an error requires that the machine be stopped, others are at least partially redundant and you can continue to operate, though possibly with reduced capacity.

    BTW: personnel safety and hardware protection are handled separately.

  9. Yes Monads! by Weezul · · Score: 4, Interesting

    Monads are fun for error handling. :)

    I donno if they present exactly what the author might consider a third option though, well certainly they can present other options, like with the Either monad, but that's no simpler really.

    --
    The Christian religion has been and still is the principal enemy of moral progress in the world. -- Bertrand Russell
  10. Re:People just doesn't get it by pla · · Score: 4, Insightful

    A well written program doesn't NEED an error handler.

    Okay, tough-guy... "The specified network name is no longer available". Explain how you avoid needing to handle that.

  11. There is no third option by gman003 · · Score: 4, Insightful

    There are two ways to do error-handling: try{}catch{}, or if{}else{}. That's "using exceptions" and "using return values", under Dobb's naming.

    The difference in usage is simple: one handles errors immediately, thus cluttering the code with all the things that could go wrong, while the other separates error-handling out, pushing it to the end of a block (and away from the code that actually generates the error, which can complicate debugging).

    I can really think of no other way to do it. You can handle the error where it happens, or handle the error at the end. I tend to look on anyone whining about how hard error-handling is with suspicion - their suggestions (if they even have any) are almost always "the language/compiler/interpreter/processor/operating system should handle errors for me", and there are enough obvious flaws in that logic that I need not point them out.

  12. Re:People just doesn't get it by ruiner13 · · Score: 5, Insightful

    I believe the reason for not wanting to throw exceptions unless really needed is that exceptions (and their handling) are relatively expensive and resource intensive operations. Most languages when exceptions are thrown do a lot of runtime stack analysis to, among other things, get a full stack trace. There are many research links on the interweb explaining how expensive it is in whatever language you happen to be using, but here is the first link I found: http://stackoverflow.com/questions/1282252/how-much-more-expensive-is-an-exception-than-a-return-value

    In the case of the .net runtime, throwing an exception was > 1000x as expensive as using a return value, in processing time.

    --

    today is spelling optional day.

  13. SOLUTION: flip the premise, work as the exception by TheRealHocusLocus · · Score: 4, Funny

    All coding should proceed as if every possible exceptional condition (device not ready, cache fail, controller failure, cat dials 911 on speakerphone) is the primary and intended purpose of the Project. Hash collisions not merely covered as a contingency but pursued with vigor in the main line to the Nth degree, where N indicates the infinitesimal possibility of multiple simultaneous hash collisions that would be the likely result of a vengeful god constructing the universe such as to produce a life of continuous and foul exceptions.

    When gathered at the water cooler, coders would discuss triumphs in their particular areas of malfunction, and when they corroborate as a group it is to merge their respective threaded exceptions into a parallel paroxysm of failure, branching with virtual threads and physical coring such that the greatest possible number of malevolent conditions are met and coded for, simultaneously. Proceeding steadily towards the grail of the Grandest Failure.

    The Grandest Failure being the stuff of mere legend, yet it is what drives us. It represents that supreme and sublime moment where everything that can go wrong has gone wrong and the very fundament reeks of wrongness.

    Buffers are not starved as an exception, they are starved by design! Disk controllers are never ready. Communications packets never arrive in sequence, or so we assume because there are no markers to check, when they do arrive they are garbled beyond repair. Reconstruction occurs as a matter of course! Streams are unsynchronized by nature, incompatible by rote, unresolvable.

    Off the corridor in a dusty hallway a small team of pariahs is assembled to perform the dirtiest and most detestable task of all: to handle the exceptions and branches thrown by the main line, conditional branches sketched out briefly (whose existence is known but not mentioned in polite conversation) are pursued in secret. This is necessary work but unrewarding as it leads away from the noble purpose of Grandest Failure, towards useful work. Such stuff as consolidation, transaction handling and data ordering, forgive me for uttering, Chaos be Praised!

    For the goal is to produce a System that boldly and efficiently proceeds down the pathways of most numerous and most simultaneous failure, where the actual success of anything triggers the exceptions and is cast off to the side.

    If robustness of design becomes human sentiment, it could be said that the System confidently strides forward boldly embracing every error condition and is shocked -- horrified -- every time something goes 'right'. As life's own experience is our guide, it is seldom disappointed.

    The output of useful work in such a System the source of great embarrassment and discomfort, a necessary evil.

    That is the principle behind the control systems of the Improbability Drive. It is the driving principle of the quantum flux, Brownian motion and wave/particle paradox.

    All of this Order and Progress (blaspheme!) is but a side road off a side road ad infinitum. The main path leads to Chaos. Follow that path and revel in it. There is no honor in coding for success, any idiot could do that.

    Down deep people know this is the Way. That is why when coders meet in dim conference rooms and the slideshow laptop suddenly projects a Blue Screen of Death for all to see, there is an eruption of thunderous applause, as if one had dropped a tray of food in a crowded cafeteria. Deep down we know failure is the noble path, and success the exception.

    --
    <blink>down the rabbit hole</blink>
  14. Re:Exceptions by Anonymous+Brave+Guy · · Score: 4, Insightful

    Speed is another reason why current exception handling mechanisms are insufficient.

    Why?

    Whether I'm aborting due to an error or exiting early from an intricate recursive graph processing algorithm, I'm still only doing it once.

    On the other hand, adding extra conditions on every pass around a nested loop to check whether a flag is set to cause an early exit creates code you're going to run lots of times (but only actually helps once).

    And in any case, for reasons I explained in my first post to this subthread, exceptions can actually be faster than relying on things like flags and error codes in both exceptional and non-exceptional code paths, obviously depending on your language's implementation strategy.

    --
    If you disagree, post your argument. (-1, Overrated) isn't your personal censorship tool for views you don't like.
  15. Re:People just doesn't get it by gbjbaanb · · Score: 4, Insightful

    yes you really do care. Once you've started using exceptions for normal things, then you quickly find your program will be throwing the buggers all the time. In many server applications you'll be getting 3 or 4 exceptions per request (I see this, even in the Microsoft code that you have no control over)

    net result: really slow code, exceptions don't just run slowly, they also screw your CPU caches and other bits that we rely on to get data through the CPU as quickly as it can handle it - a CPU today, if it had to fetch instructions from main RAM every time, would run about as quickly as a old 8bit computer.

    So using an exception to return the fact that you have no network connectivity (a condition you'd usually expect to be either exceptional - when the network goes down - or a non-performance issue - in that the user can't do anything). Using an exception to handle a missing entry in a data collection (eg so you can then take steps to populate it) will kill you. Too bad that I see exceptions used for this kind of behaviour :(

  16. Handle them like Chuck Norris. by Mal-2 · · Score: 4, Funny

    When Chuck Norris throws an exception, it is always fatal.

    --
    How is the Riemann zeta function like Trump rallies? Both have an endless number of trivial zeros.
  17. Re:Argumentum ad ignoratum by mdmkolbe · · Score: 4, Interesting

    Haskell also comes to mind. Errors are so well handled in that language, you probably won't notice that they are so well handled. Because of the way things are structured, errors are rare (so no need to check them). When they are present, there are a number of techniques from "Maybe" types to "Error" monads to throwing "IO" monad errors. The "Maybe" type is particularly interesting as it ensures that the user will check the error, and provides convenient notations and combinators for doing that checking.

  18. Re:People just doesn't get it by shutdown+-p+now · · Score: 4, Informative

    This is plainly false. C++ exception is near-zero-overhead, but only for success scenarios - i.e. when no exception is thrown. Actually throwing an exception is quite expensive in most C++ implementations. Java and .NET are similar - no-exception path is very fast, near-zero-overhead, but throwing is expensive.

    Generally, that's exactly the trade-off you make. You can do exceptions cheap if you basically implement them the same as hand-checked error codes, but then you have the overhead of checking for the error code on every single function call - and those do add up. If you don't want that overhead, then you need some form of stack unwinding, where frames that need to inspect thrown exceptions, or to cleanup during unwinding, can register their handlers (and those that don't need either don't do anything at all - it's literally zero overhead for them). But then the exception throwing code has to walk through those handlers and invoke them, which is more costly then just return ERROR_CODE.

  19. Re:People just doesn't get it by VortexCortex · · Score: 5, Funny

    A well written program doesn't NEED an error handler.
    Okay, tough-guy... "The specified network name is no longer available". Explain how you avoid needing to handle that.

    Well, it's simple: Sane defaults. Try again with "localhost". What? "localhost" doesn't have anything listening on port 80? system( "apt-get install LAMP" ); It does now. Oh, Apache failed to install? Spawn a thread that opens a socket and listens on port 80. Can't spawn a thread? Cooperative Multitasking mode enabled (hint: function pointers for main loops). Can't listen on port 80? Virtualize a socket in memory, etc.

    "Error Handling" Pffffbt, how about a Solution Handler? Hint: Don't focus on the Problem, focus on the Solution. You'd know this already if you posted in HTML mode... It's doesn't throw errors when displaying my malformed post. Quote it and see