Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. Design and Architecture
  4. Exception or Return Value?

Exception or Return Value?

Scheduled Pinned Locked Moved Design and Architecture
questionhelp
8 Posts 7 Posters 52 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • Richard Andrew x64R Offline
    Richard Andrew x64R Offline
    Richard Andrew x64
    wrote on last edited by
    #1

    What is the rule of thumb for deciding whether to throw an exception or return an error code when something goes wrong?

    The difficult we do right away... ...the impossible takes slightly longer.

    Greg UtasG Mircea NeacsuM Richard DeemingR I 4 Replies Last reply
    0
    • Richard Andrew x64R Richard Andrew x64

      What is the rule of thumb for deciding whether to throw an exception or return an error code when something goes wrong?

      The difficult we do right away... ...the impossible takes slightly longer.

      Greg UtasG Offline
      Greg UtasG Offline
      Greg Utas
      wrote on last edited by
      #2

      It may depend on your application and whatever is standard practice in your existing code base, if you're dealing with one. For a system that handles lots of transactions, I strongly advise using an exception only if a transaction should be aborted because of a serious error that also gets logged for debugging. The exception gets caught well down the stack, where bulletproof recovery and logging are initiated. In this type of system, it is very rare for application code to catch exceptions. The general problem with exceptions is that the caller must know that a function will throw. Even if this is documented by keywords or comments, will the catch actually get written? Nothing forces it to be, whereas it's harder to ignore an error code. And if the catch isn't written, the exception trickles down the stack. What can anyone else make of it? Ultimately it's up to that bulletproof code unless crashing is OK. Exceptions also have more overhead than error codes, not only in CPU time but in code bulk. There's also the question of where the finger of blame should point. If someone passes your function a null pointer and you use it, guess where the SIGSEGV occurs? So it's your code that ends up looking crappy, even if the stack trace can point you to the real culprit. I therefore make it a habit to check arguments for validity and to generate a log and return an error code if one is found to be nonsense. This also makes debugging easier for everyone. It'd be hard to convince me that a system should use exceptions other than sparingly. Having a system that mixes error codes and exceptions seemingly at random makes no sense.

      Robust Services Core | Software Techniques for Lemmings | Articles
      The fox knows many things, but the hedgehog knows one big thing.

      <p><a href="https://github.com/GregUtas/robust-services-core/blob/master/README.md">Robust Services Core</a>
      <em>The fox knows many things, but the hedgehog knows one big thing.</em></p>

      O 1 Reply Last reply
      0
      • Richard Andrew x64R Richard Andrew x64

        What is the rule of thumb for deciding whether to throw an exception or return an error code when something goes wrong?

        The difficult we do right away... ...the impossible takes slightly longer.

        Mircea NeacsuM Offline
        Mircea NeacsuM Offline
        Mircea Neacsu
        wrote on last edited by
        #3

        There is no rule of thumb for choosing between the two. Each one has advantages and disadvantages. There are also more "modern" solutions like std::expected and boost::outcome. If you want some rules of thumb: - Be consistent. If you have some functions returning an error code and others throwing exceptions you can easily create a big mess. - Design your error handling mechanism early. Retrofitting any error mechanism is very painful This may sound terribly immodest, but my own solution, a cross between exceptions and error codes, still seems to me the best compromise. I've used it for almost 20 years so most of it is battle hardened code. The code in the article is a bit old so you might be better off grabbing the latest version from GitHub.

        Mircea

        T 1 Reply Last reply
        0
        • Richard Andrew x64R Richard Andrew x64

          What is the rule of thumb for deciding whether to throw an exception or return an error code when something goes wrong?

          The difficult we do right away... ...the impossible takes slightly longer.

          Richard DeemingR Offline
          Richard DeemingR Offline
          Richard Deeming
          wrote on last edited by
          #4

          Eric Lippert provided a good classification of the different types of exceptions back in 2008: Vexing exceptions | Fabulous adventures in coding[^] Whilst he doesn't provide much specific advice, he does say:

          Quote:

          Try to never write a library yourself that throws a vexing exception.

          where a "vexing" exception is one that is "thrown in a completely non-exceptional circumstance" - eg: Int32.Parse.


          "These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer

          "These people looked deep within my soul and assigned me a number based on the order in which I joined" - Homer

          1 Reply Last reply
          0
          • Mircea NeacsuM Mircea Neacsu

            There is no rule of thumb for choosing between the two. Each one has advantages and disadvantages. There are also more "modern" solutions like std::expected and boost::outcome. If you want some rules of thumb: - Be consistent. If you have some functions returning an error code and others throwing exceptions you can easily create a big mess. - Design your error handling mechanism early. Retrofitting any error mechanism is very painful This may sound terribly immodest, but my own solution, a cross between exceptions and error codes, still seems to me the best compromise. I've used it for almost 20 years so most of it is battle hardened code. The code in the article is a bit old so you might be better off grabbing the latest version from GitHub.

            Mircea

            T Offline
            T Offline
            trønderen
            wrote on last edited by
            #5

            Mircea Neacsu wrote:

            If you have some functions returning an error code and others throwing exceptions you can easily create a big mess.

            This sounds to me like 'Use either exceptions or error codes in your program - never both'. To me, that is similar to 'Define either errors or warnings - never both'. But of course you will not define all warnings as errors.

            Mircea Neacsu wrote:

            my own solution, a cross between exceptions and error codes

            I am really happy that you added this :-) I hope readers see this as your primary advice, rather than the either/or thinking that you introduced in the beginning. If you run into a situation that the caller can handle then and there, and go on, is different from a situation which is fatal to some significant operation, so it has to be abandoned. If you want a rule of thumb (but one with many exceptions): If a caller can handle an error code, restore to a 'normal' condition and continue, with no significant operation aborted, the an error code is appropriate. If handling the situation back to normal cannot be done by the caller after the return, but must be reported to some outer level (and possibly to the user), then an exception is more appropriate. The borderline is certainly not sharp (nor is the line between warnings and errors!), and often a design selection. Some people/environments have raised a 'robustness principle' (based on the rule 'Be tolerant with others, and strict with yourself', codified in RFC 761), doing what is possible recover and continue, while others want to expose, not gloss over problems (e.g. OSI stack protocols, disconnecting on any protocol violations).

            Religious freedom is the freedom to say that two plus two make five.

            Mircea NeacsuM 1 Reply Last reply
            0
            • T trønderen

              Mircea Neacsu wrote:

              If you have some functions returning an error code and others throwing exceptions you can easily create a big mess.

              This sounds to me like 'Use either exceptions or error codes in your program - never both'. To me, that is similar to 'Define either errors or warnings - never both'. But of course you will not define all warnings as errors.

              Mircea Neacsu wrote:

              my own solution, a cross between exceptions and error codes

              I am really happy that you added this :-) I hope readers see this as your primary advice, rather than the either/or thinking that you introduced in the beginning. If you run into a situation that the caller can handle then and there, and go on, is different from a situation which is fatal to some significant operation, so it has to be abandoned. If you want a rule of thumb (but one with many exceptions): If a caller can handle an error code, restore to a 'normal' condition and continue, with no significant operation aborted, the an error code is appropriate. If handling the situation back to normal cannot be done by the caller after the return, but must be reported to some outer level (and possibly to the user), then an exception is more appropriate. The borderline is certainly not sharp (nor is the line between warnings and errors!), and often a design selection. Some people/environments have raised a 'robustness principle' (based on the rule 'Be tolerant with others, and strict with yourself', codified in RFC 761), doing what is possible recover and continue, while others want to expose, not gloss over problems (e.g. OSI stack protocols, disconnecting on any protocol violations).

              Religious freedom is the freedom to say that two plus two make five.

              Mircea NeacsuM Offline
              Mircea NeacsuM Offline
              Mircea Neacsu
              wrote on last edited by
              #6

              trønderen wrote:

              But of course you will not define all warnings as errors

              You are right. I should have said: "for similar situations use either errors or exceptions." For sure you can use both if you do it in a consistent manner.

              trønderen wrote:

              If a caller can handle an error code, restore to a 'normal' condition and continue, with no significant operation aborted, the an error code is appropriate. If handling the situation back to normal cannot be done by the caller after the return, but must be reported to some outer level (and possibly to the user), then an exception is more appropriate.

              Indeed! The way I see it, the conundrum of error handling is that, at lower levels you have all the information about what happened but you cannot make any decision. At higher levels, you can make decisions but the amount of information you have is limited (errors have been coerced in a few error codes, exceptions have limited information, etc.). This is not unlike the situation in any organization where higher up executives have increasing decision power and decreasing knowledge about what's going on. Finding the appropriate compromise is difficult both for error handling and for organizations. Going back to my error code objects solution, one more thing I particularly like is that it makes it immediately clear what functions return error codes. Looking at the signature of a function like:

              int read (FILE* f, void* data, int& len);

              you cannot immediately know if the returned value is the number of bytes read, or an error code or a combination of those. Meanwhile, with my system, a function signature like:

              erc read (FILE* F, void* data, int& len);

              it is clear that it returns an error code. Said error code magically transforms into an exception if not properly treated :)

              Mircea

              1 Reply Last reply
              0
              • Greg UtasG Greg Utas

                It may depend on your application and whatever is standard practice in your existing code base, if you're dealing with one. For a system that handles lots of transactions, I strongly advise using an exception only if a transaction should be aborted because of a serious error that also gets logged for debugging. The exception gets caught well down the stack, where bulletproof recovery and logging are initiated. In this type of system, it is very rare for application code to catch exceptions. The general problem with exceptions is that the caller must know that a function will throw. Even if this is documented by keywords or comments, will the catch actually get written? Nothing forces it to be, whereas it's harder to ignore an error code. And if the catch isn't written, the exception trickles down the stack. What can anyone else make of it? Ultimately it's up to that bulletproof code unless crashing is OK. Exceptions also have more overhead than error codes, not only in CPU time but in code bulk. There's also the question of where the finger of blame should point. If someone passes your function a null pointer and you use it, guess where the SIGSEGV occurs? So it's your code that ends up looking crappy, even if the stack trace can point you to the real culprit. I therefore make it a habit to check arguments for validity and to generate a log and return an error code if one is found to be nonsense. This also makes debugging easier for everyone. It'd be hard to convince me that a system should use exceptions other than sparingly. Having a system that mixes error codes and exceptions seemingly at random makes no sense.

                Robust Services Core | Software Techniques for Lemmings | Articles
                The fox knows many things, but the hedgehog knows one big thing.

                O Offline
                O Offline
                OVO Clothing
                wrote on last edited by
                #7

                OVO Clothing || October's Very Own || Limited Stock[[^](https://ovoclotOctober's Very Own commonly known as OVO Clothing is Drake's Official clothing Brand. We are offering upto 50% OFF on Latest OVO Collection.

                hing.ltd/ "New Window")]

                1 Reply Last reply
                0
                • Richard Andrew x64R Richard Andrew x64

                  What is the rule of thumb for deciding whether to throw an exception or return an error code when something goes wrong?

                  The difficult we do right away... ...the impossible takes slightly longer.

                  I Offline
                  I Offline
                  InShotsPro
                  wrote on last edited by
                  #8

                  **Use Exceptions When:**

                  • Errors are unexpected and disrupt normal flow.
                  • Error handling is complex and needs separation from normal code.
                  • You need to propagate errors up the call stack or provide detailed debugging information.

                  **Use Error Codes When:**

                  • Performance is a concern and you want to avoid the overhead of exceptions.
                  • Errors are expected and can be managed at the current level.
                  • The return value already indicates success or failure, and adding exceptions would complicate the API.

                  In summary, exceptions are for unexpected issues requiring detailed handling, while error codes are for expected issues with simpler management.

                  1 Reply Last reply
                  0
                  Reply
                  • Reply as topic
                  Log in to reply
                  • Oldest to Newest
                  • Newest to Oldest
                  • Most Votes


                  • Login

                  • Don't have an account? Register

                  • Login or register to search.
                  • First post
                    Last post
                  0
                  • Categories
                  • Recent
                  • Tags
                  • Popular
                  • World
                  • Users
                  • Groups