December 11, 2010

cazador7907 cazador7907
Lab Rat
78 posts

Exception Handling, Throwing Exception and Try/Catch blocks

Page  
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?

  1. GraphNode* Graph::GetGraphNode(const QString name)
  2. {
  3.     foreach( GraphNode *currNode, nodeList )
  4.     {
  5.         if(currNode->Name() == name)
  6.             return currNode;
  7.     }
  8.  
  9.     return NULL;
  10. }

  1. void Graph::AddEdge(QString from, QString to, double cost)
  2. {
  3.     //Locals
  4.     GraphNode* fromTerminal = GetGraphNode(from);
  5.     GraphNode* toTerminal = GetGraphNode(to);
  6.  
  7.     if( fromTerminal == NULL || toTerminal == NULL )
  8.     {
  9.         qDebug() << "Cannot add an Edge with a NULL terminus.";
  10.         throw()
  11.     }
  12.     else
  13.     {
  14.         //Add the Edge
  15.         nodeList[fromTerminal->Index()]->AddEdge(fromTerminal->Index(),
  16.                                                  toTerminal->Index(),
  17.                                                  cost);
  18.         nodeList[toTerminal->Index()]->AddEdge(toTerminal->Index(),
  19.                                                fromTerminal->Index(),
  20.                                                cost);
  21.     }
  22.  
  23. }

 Signature 

Laurence -

 

34 replies

December 11, 2010

Gerolf Gerolf
Area 51 Engineer
3211 posts

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 [amazon.com]

 Signature 

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

December 11, 2010

cazador7907 cazador7907
Lab Rat
78 posts

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?

 Signature 

Laurence -

 

December 11, 2010

Gerolf Gerolf
Area 51 Engineer
3211 posts

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.

 Signature 

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

December 11, 2010

Denis Kormalev Denis Kormalev
Lab Rat
1654 posts

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.

December 11, 2010

Wolf P. Wolf P.
Ant Farmer
354 posts

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:

  1. class GeneralError { /* Your runtime error base class */ };
  2. // (exception class hierarchies are often much deeper than 2 levels)
  3. class DecodingError: public GeneralError {  /* One of your specific runtime errors */ };
  4. // 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”):

  1. try {
  2.     // do something, maybe in a loop within subroutines
  3.     // that will trow specific errors for instance DecodingError
  4. } catch (GeneralError& e) {
  5.     // here your application seems to be at the end,
  6.     // because you have no specific handling for general errors
  7. }

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

December 11, 2010

Wolf P. Wolf P.
Ant Farmer
354 posts

Oh I forgot:

(1)

  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.

December 11, 2010

Wolf P. Wolf P.
Ant Farmer
354 posts

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?

December 11, 2010

cazador7907 cazador7907
Lab Rat
78 posts

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 –

 Signature 

Laurence -

 

December 11, 2010

cazador7907 cazador7907
Lab Rat
78 posts

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

 Signature 

Laurence -

 

December 11, 2010

Bradley Bradley
Lab Rat
314 posts

Qt is exception safe for the most part. Here is some documentation [doc.trolltech.com]

 Signature 

Nokia Certified Qt Specialist.

December 11, 2010

Wolf P. Wolf P.
Ant Farmer
354 posts

Bradley wrote:
Qt is exception safe for the most part. Here is some documentation [doc.trolltech.com]

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.

December 11, 2010

Bradley Bradley
Lab Rat
314 posts
Wolf P. wrote:
automatic objects (=variables declared per value on the stack) crash

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

 Signature 

Nokia Certified Qt Specialist.

December 11, 2010

cazador7907 cazador7907
Lab Rat
78 posts

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.

 Signature 

Laurence -

 

December 11, 2010

Gerolf Gerolf
Area 51 Engineer
3211 posts

Qt is not using error numbers in all cases, some functions just tell success / fail (True / false). QFie [doc.qt.nokia.com] uses error numbers QFile::error() [doc.qt.nokia.com] 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).

 Signature 

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

December 11, 2010

Wolf P. Wolf P.
Ant Farmer
354 posts

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.

Page  
1

  ‹‹ What exactly does "Clipping" mean when we talk about painting in Qt?      QProgressBar Chunk ››

You must log in to post a reply. Not a member yet? Register here!