Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • Users
  • Groups
  • Search
  • Get Qt Extensions
  • Unsolved
Collapse
Brand Logo
  1. Home
  2. Qt Development
  3. General and Desktop
  4. Exception Handling, Throwing Exception and Try/Catch blocks
Forum Updated to NodeBB v4.3 + New Features

Exception Handling, Throwing Exception and Try/Catch blocks

Scheduled Pinned Locked Moved General and Desktop
37 Posts 7 Posters 73.1k 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.
  • C Offline
    C Offline
    cazador7907
    wrote on 11 Dec 2010, 19:18 last edited by
    #1

    I wrote a short function "AddEdge" that adds an edge object to a graph object (I've put the code at the end of this post). In this function, I retrieve the "From" and "To" nodes that form the terminal ends of the edge using another function called "GetGraphNode". This second function will either return a pointer to the proper node or a NULL (this code is also at the end of this post).

    Once I have references to the terminal nodes, I then test to make sure that both references are not null. The rule being that if either of the references is NULL then nothing happens the function exits normally without adding the edge to the graph.

    What I would like to do to is have the function raise an exception so that the calling program can know that there is a problem and can do something (write to a log probably). However, when I started looking into Qt and exceptions, I didn't find to much information. I did find a couple of articles on writing my own exceptions and using those.

    So, is there any advice, articles, white papers, direction, suggestions for handling exceptions within a Qt application? Also, in thinking about how to log errors and the like, is there an excepted way keep a log of errors?

    @
    GraphNode* Graph::GetGraphNode(const QString name)
    {
    foreach( GraphNode *currNode, nodeList )
    {
    if(currNode->Name() == name)
    return currNode;
    }

    return NULL;
    

    }
    @

    @void Graph::AddEdge(QString from, QString to, double cost)
    {
    //Locals
    GraphNode* fromTerminal = GetGraphNode(from);
    GraphNode* toTerminal = GetGraphNode(to);

    if( fromTerminal == NULL || toTerminal == NULL )
    {
        qDebug() << "Cannot add an Edge with a NULL terminus.";
        throw()
    }
    else
    {
        //Add the Edge
        nodeList[fromTerminal->Index()]->AddEdge(fromTerminal->Index(),
                                                 toTerminal->Index(),
                                                 cost);
        nodeList[toTerminal->Index()]->AddEdge(toTerminal->Index(),
                                               fromTerminal->Index(),
                                               cost);
    }
    

    }
    @

    Laurence -

    1 Reply Last reply
    0
    • G Offline
      G Offline
      giesbert
      wrote on 11 Dec 2010, 19:27 last edited by
      #2

      Hi,

      Qt is not using exceptions for errors. So I think, that's why there ios no documentation about that. You can use exceptions, if you want. My personal opinion is to use error codes instead of exceptions, but that's a matter of taste. I know many people using exceptions and many using error codes. Both works. But you have to create your own exceptions for that. I would suggest using std::exception as base class.
      If you want to know more about exceptions, I would advise reading "Exceptional C++ from Herb Sutter":http://www.amazon.com/dp/0201615622

      Nokia Certified Qt Specialist.
      Programming Is Like Sex: One mistake and you have to support it for the rest of your life. (Michael Sinz)

      1 Reply Last reply
      0
      • C Offline
        C Offline
        cazador7907
        wrote on 11 Dec 2010, 19:40 last edited by
        #3

        Interesting. I will look into using Error Codes as well for I jump one or the other.

        But, your response begs to ask the most obvious question. Qt seems to me to be a very mature development suite easily on par with XCode or VS. Why would it's developers not implement exceptions for errors?

        Laurence -

        1 Reply Last reply
        0
        • G Offline
          G Offline
          giesbert
          wrote on 11 Dec 2010, 19:53 last edited by
          #4

          Why should they?

          Exceptions have advantages and disadvantages:

          plus:

          • Easy exit of the application / function
          • can contain any information (text, code etc, also combined)

          minus:

          • slower execution (exceptions transportation code must be added and is added to all functions)
          • more binary code (+ ~10% - 15%)
          • If you have exceptiosn and don't use smart pointers, cleanup is often buggy --> heap objects stay where they are etc.

          Nokia Certified Qt Specialist.
          Programming Is Like Sex: One mistake and you have to support it for the rest of your life. (Michael Sinz)

          1 Reply Last reply
          0
          • D Offline
            D Offline
            DenisKormalev
            wrote on 11 Dec 2010, 19:55 last edited by
            #5

            cazador7907, exception-way or errno-way are equal ways. I can't say that one is better than another. They are simply different. Qt chose errno-way at the beginning and uses it now.

            P 1 Reply Last reply 19 May 2017, 12:57
            0
            • W Offline
              W Offline
              Wolf P.
              wrote on 11 Dec 2010, 20:15 last edited by
              #6

              You can use exceptions also with Qt, when the compiler supports it. You should know that your code will be less portable then. Exceptions are not bad.

              But each exception you throw, you have to catch. You cannot shift catching to some point in the far future, you should think about catching before throwing.

              And you should know exception handling patterns. The most important is in my opinion: to throw never a less specific exception then you will catch in the call stack. Here a simple example:

              @
              class GeneralError { /* Your runtime error base class / };
              // (exception class hierarchies are often much deeper than 2 levels)
              class DecodingError: public GeneralError { /
              One of your specific runtime errors */ };
              // many more of specific error classes in your application follow here...
              @

              The following in the context of some top-level function (considered to be a "subsystem"):
              @
              try {
              // do something, maybe in a loop within subroutines
              // that will trow specific errors for instance DecodingError
              } catch (GeneralError& e) {
              // here your application seems to be at the end,
              // because you have no specific handling for general errors
              }
              @

              Generally I'd prefer using exceptions to portability (if portability is not actually needed).

              1 Reply Last reply
              0
              • W Offline
                W Offline
                Wolf P.
                wrote on 11 Dec 2010, 20:22 last edited by
                #7

                Oh I forgot:

                (1)
                @
                throw;
                @
                can only be used within catch blocks.

                (2)
                Exceptions are better than assert. Qt will kill your application when you access a QList with the at() function out of range. And this I find is a bad idea, but you have todo something exceptional on range errors, else your program will (mis)behave random.

                1 Reply Last reply
                0
                • W Offline
                  W Offline
                  Wolf P.
                  wrote on 11 Dec 2010, 20:25 last edited by
                  #8

                  Maybe I'm wrong. But if not, and exceptions (on application programmer's level) can be used with Qt, should we/I add a page in the wiki?

                  1 Reply Last reply
                  0
                  • C Offline
                    C Offline
                    cazador7907
                    wrote on 11 Dec 2010, 20:37 last edited by
                    #9

                    Not that I want to appear helpless but, I've can't seem to located information on how to using Qt and error number/codes or error handling in general.

                    Would someone please point me in the right direction?

                    Laurence -

                    Laurence -

                    1 Reply Last reply
                    0
                    • C Offline
                      C Offline
                      cazador7907
                      wrote on 11 Dec 2010, 20:47 last edited by
                      #10

                      I think that a wiki page is a fantastic idea! Perhaps including some comparative information on Exception handing vs. Error Numbers?

                      Laurence -

                      1 Reply Last reply
                      0
                      • B Offline
                        B Offline
                        baysmith
                        wrote on 11 Dec 2010, 20:47 last edited by
                        #11

                        Qt is exception safe for the most part. Here is some "documentation":http://doc.trolltech.com/4.7-snapshot/exceptionsafety.html

                        Nokia Certified Qt Specialist.

                        1 Reply Last reply
                        0
                        • W Offline
                          W Offline
                          Wolf P.
                          wrote on 11 Dec 2010, 20:59 last edited by
                          #12

                          [quote author="Bradley" date="1292100479"]Qt is exception safe for the most part. Here is some "documentation":http://doc.trolltech.com/4.7-snapshot/exceptionsafety.html [/quote]
                          Oh that's bad :( - I mean it's clear, that I have to care for pointers myself, but if automatic objects (=variables declared per value on the stack) crash, than I should rethink thoroughly my idea of combining exceptions with Qt.

                          1 Reply Last reply
                          0
                          • B Offline
                            B Offline
                            baysmith
                            wrote on 11 Dec 2010, 21:09 last edited by
                            #13

                            [quote author="Wolf P." date="1292101141"]automatic objects (=variables declared per value on the stack) crash[/quote]

                            It states that "Common cases should work". There will always be exceptional cases. I think for the most part it isn't a problem.

                            Nokia Certified Qt Specialist.

                            1 Reply Last reply
                            0
                            • C Offline
                              C Offline
                              cazador7907
                              wrote on 11 Dec 2010, 21:24 last edited by
                              #14

                              My question though revolves around implementing custom handlers. In the example code that I copied into the original post there is a situation where a NULL pointer could be returned which would cause the AddEdge to fail. In the case of the code above the failure is silent (i.e. nothing happens).

                              However, I would like to have the function raise an error message so that program can let me know that there was error and then exit - I hope - gracefully.

                              Based on what I've been reading, I have two choices: Writing my own Exception Handlers or using Qt native error numbers. is that correct?

                              I haven't really found anything in the Qt documentation that discusses implementing custom error handling (i.e. trapping NULLs, DIV/0, Bad Memory Allocations, etc.). Is there material out there that discusses the creation of custom error handling?

                              Hopefully, I'm not making this harder than it should be.

                              Laurence -

                              1 Reply Last reply
                              0
                              • G Offline
                                G Offline
                                giesbert
                                wrote on 11 Dec 2010, 21:49 last edited by
                                #15

                                Qt is not using error numbers in all cases, some functions just tell success / fail (True / false). "QFie":http://doc.qt.nokia.com/4.7/qfile.html uses error numbers "QFile::error()":http://doc.qt.nokia.com/4.7/qfile.html#error for example.
                                And take care: Exception handling catches custom exceptions, no structured exception like null pointer access, division by 0 etc.
                                That can be handled by structured exception handling (windows) or signal handlers (Linux).

                                Nokia Certified Qt Specialist.
                                Programming Is Like Sex: One mistake and you have to support it for the rest of your life. (Michael Sinz)

                                1 Reply Last reply
                                0
                                • W Offline
                                  W Offline
                                  Wolf P.
                                  wrote on 11 Dec 2010, 22:12 last edited by
                                  #16

                                  cazador7907, I think in the case of your Graph::AddEdge method, returning a bool would be much better. It was also possible to use two GraphNode& parameters and resolve the names before you call the method. Then the problem - if any at all - will be outside the method (as you wished).

                                  If you insist in doing it the exceptional way, you have to classify the errors in your application first.

                                  Error handling is always hard. If you decide to use exception handling, you have to be more consistent in comparison to error codes: the ignore-option isn't available when exceptions are thrown.

                                  1 Reply Last reply
                                  0
                                  • G Offline
                                    G Offline
                                    goetz
                                    wrote on 12 Dec 2010, 21:19 last edited by
                                    #17

                                    cazador, there is no such thing like "Qt native error numbers". You will have to define them yourself, probably as an enum in a class or namespace of your application.

                                    As the others already said, alternatively, you can also use exceptions for your own error handling.

                                    If you go with error numbers or exceptions is to a certain degree a matter of taste. But there are some reasons, that favor exceptions (e.g. the "C++ FAQ on exceptions":http://www.parashift.com/c++-faq-lite/exceptions.html, it lists some cases, that are difficult to handle with error numbers, but easy with exceptions). I successfully integrated another lib, that uses exceptions for error handling with Qt (ImageMagick/GraphicsMagick, if you care).

                                    The reason why Qt does not use exceptions is more or less historical. You have to know that the very first implementation was made over 12 years ago. At that time compilers supporting exceptions were not very common. This holds true for the 3.x series too, that was initially released in 2001. I think even the 4.x series was supposed to build with compilers in 2005 that did not yet support exceptions. I would not bet, that they ignore exceptions for the 5.x series too :-)

                                    http://www.catb.org/~esr/faqs/smart-questions.html

                                    1 Reply Last reply
                                    0
                                    • C Offline
                                      C Offline
                                      cazador7907
                                      wrote on 13 Dec 2010, 01:09 last edited by
                                      #18

                                      How do I define my own error number? I might have missed it in my searches but I cannot find any guidance in the Qt documentation.

                                      Laurence -

                                      1 Reply Last reply
                                      0
                                      • B Offline
                                        B Offline
                                        baysmith
                                        wrote on 13 Dec 2010, 02:19 last edited by
                                        #19

                                        There is nothing special about error numbers. They are just numbers used in some context and based on the context the represent some error state.

                                        Nokia Certified Qt Specialist.

                                        1 Reply Last reply
                                        0
                                        • W Offline
                                          W Offline
                                          Wolf P.
                                          wrote on 13 Dec 2010, 08:54 last edited by
                                          #20

                                          [quote author="cazador7907" date="1292202586"]How do I define my own error number? I might have missed it in my searches but I cannot find any guidance in the Qt documentation.[/quote]
                                          If you are not familiar with error numbers:

                                          @
                                          /// this is a enumeration of all error conditions "I currently know"
                                          enum MyRunTimeErrors {
                                          MY_SUCCESS_CODE,
                                          MY_INDEX_OUT_OF_BOUNDS,
                                          MY_NULL_POINTER_NOT_ALLOWED,
                                          MY_INVALID_RANGE
                                          };

                                          /// this is a placeholder function handling all "currently known" errors
                                          void test() {
                                          const int error = doSomethingNonTrivial(); // in this call several errors can occur
                                          switch (error) {
                                          code MY_SUCCESS_CODE:
                                          // All went good :)
                                          // Make anything else here...
                                          break;

                                          code MY_INDEX_OUT_OF_BOUNDS:
                                            // Handle index not inside the valid bounds of an array (a list)
                                            break;
                                          
                                          code MY_NULL_POINTER_NOT_ALLOWED:
                                            // Handle unsuported null pointer
                                            break;
                                          
                                          code MY_INVALID_RANGE:
                                            // Handle numeric range miss, maybe by an input
                                            break;
                                          
                                          default:
                                            // Oops, who (me ??) did something wrong, and especially: WHAT?
                                            traceError("Internal Error: Unknown Error detected #%d", error);
                                            break;
                                          

                                          }
                                          }
                                          @

                                          ..., leave this out, study exception handling today!

                                          The exception-based way is much better, since you can group error conditions and decide from case to case how specific your handling should be. You get a second channel for error detection, error transmission, error handling. Exceptions are not used yet in Qt, but (my glass ball says:) it will (it has to) come that we can switch them on optionally.

                                          1 Reply Last reply
                                          0

                                          1/37

                                          11 Dec 2010, 19:18

                                          • Login

                                          • Login or register to search.
                                          1 out of 37
                                          • First post
                                            1/37
                                            Last post
                                          0
                                          • Categories
                                          • Recent
                                          • Tags
                                          • Popular
                                          • Users
                                          • Groups
                                          • Search
                                          • Get Qt Extensions
                                          • Unsolved