Important: Please read the Qt Code of Conduct -

Exception Handling, Throwing Exception and Try/Catch blocks

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

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

  • Qt is exception safe for the most part. Here is some "documentation":

  • [quote author="Bradley" date="1292100479"]Qt is exception safe for the most part. Here is some "documentation": [/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.

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

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

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

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

  • 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":, 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 :-)

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

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

  • [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 {

    /// 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) {
    // All went good :)
    // Make anything else here...

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


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

  • Hi Wolf, exceptions or not is a matter of taste, as Volker said. I suggest using error number more than exceptions. If you want to ignore the error, that's easy with error numbers not with exceptions. If the exceptions are not 100% cleard efined in the throws, it's hgard to know, which exceptions are thrown and should be catched. And in many places, where exceptions are used for errors, I see only this:

    // do some stuff that might throw an exception
    // do something

    And then, exceptions do NOT make sense.

  • When you find this style of exception handling "used" everywhere in your project
    catch (...) { /* indeed: do NOTHING */ }
    ...then it's a sure sign of ignorance. I think those, who try to skip analysis, understanding and classification of errors, will never succeed in error handling. Skipping default in switch is equivalent to catch all clauses anywhere in the code.

    Of course, you can classify errors using numeric codes. But that's hard work.

  • Wolf P., again it's just matter of taste. For me errno way is much simplier error handling than exception-way.

  • For me too. If I want to handle the errors, I can handle one or more errors in the same way, in the same block of code (via switch, if, whatever).

  • That I have to accept.
    Here something more interesting, I've found googling for "Qt exception exec":
    "Qt: Throw exceptions from signals and slots":
    For those who like exceptions it may be interesting ,if not already known.

  • This means, no exceptions from slots and event handlers. Or re-implement that function, but you can't handle them in the main if they are thrown in the event loop. And what to do in event loops in threads?

  • (1) Generally, it seems not to be possible to throw exceptions through the libraries of the operating system.
    (2) I'm not yet familiar with threads in Qt. What is the standard event loop for an additional thread?

  • QEventLoop :-))
    And throwing exceptions via libraries is not the problem. But perhaps the QApplication eventloop catches them? I didn't look at the QtCode for that up to now.

  • I catch the exceptions in the methods, where I call the lib's functions. In my special case, there is no event loop that can make things bad.

  • Gerolf, QEventLoop has no signals and no virtual function, so... In this issue I need to familiarize myself first...
    (and: I don't think that you can throw an exception through a binary dynamic link library (with a C API).)

  • You're right. C does not provide exceptions. You would have to write a C++ wrapper that adds this and that probably makes the API more OO-like (that's what the ImageMagick/GraphicsMagick guys did).

  • [quote author="Volker" date="1292253297"]I catch the exceptions in the methods, where I call the lib's functions. In my special case, there is no event loop that can make things bad. [/quote] You're right. But If you forget to handle a particular exception your program crashes.
    Of course it should be terminated immidiately, but gracefully.

  • That part of the program is only very small. Basically only one class that uses the lib, and every exception that can be thrown is caught and handled in our case. But I agree, that can be hard to handle all together.

    I personally like the concept of exceptions - you can throw them and whoever is responsible catches them and handles the condition. Althoug I never used them in C++ on my own (only in Java), as there are too many pitfalls at the moment.

  • Dlls can use exceptions, wolf, if they are C++ dlls. And I don't think, that you create C dlls if you are using Qt, do you? My dlls are normally C++ dlls which export C++ classes. There it could be done, but I don't do it.
    And QEventLoop handles asynchronous signals, as QueuedSignals are in fact events :-)

  • For clarity: I am not in the least interested to write DLLs in C myself. I meant pre-existing DLLs. Try to throw an exception in a Windows callback and you'll see what I was talking about. (Sometimes you have to code against a Windows API.)

    I'm sorry that I have expressed this somewhat misleading.

  • @DenisKormalev said in Exception Handling, Throwing Exception and Try/Catch blocks:

    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.

    exception are structured way of both rise the error and handle the error
    return codes do not dictate how you handle (the mechansim) , you might even not handle it!, try doing the same with exceptions ;)

  • @giesbert tier down the application obviously ... exceptions are exceptional ...

Log in to reply