Qt5 how to catch an exception?
-
Environment
- OS: Ubuntu 20.04LTS
- Qt-Version: 5.12.8
Problem
How to catch an exception?
if my code likes thistry{ //if here occur an null_pointer_exception or io_exception,how to catch the exception? }catch(???){ ??? }or how do I turn on the switch of Qt5 and catch the exception?
-
your logic is correct but TTBOMK Qt doesn't do exceptions, so any exceptions thrown will be core c++ exceptions, and I'm not sure how well the MOC supports throwing.
Also, your description of what an exception is is lacking. nullptr should always be manually checked, and there is no such thing as io_exception. look at the core c++ exceptions to see what stl has implemented.
-
Dereferencing a nullptr will generate an operating system exception (SIGSEGV), not a C++ exception. On Linux this leads to immediate operating system termination of your application; there's little you can do about it. You might be able to catch that signal (http://www.cplusplus.com/reference/csignal/signal/) but, unless you are absolutely certain that you can recover, your program should be considered mortally wounded. It is far easier to program defensively as @Kent-Dorfman says.
-
Environment
- OS: Ubuntu 20.04LTS
- Qt-Version: 5.12.8
Problem
How to catch an exception?
if my code likes thistry{ //if here occur an null_pointer_exception or io_exception,how to catch the exception? }catch(???){ ??? }or how do I turn on the switch of Qt5 and catch the exception?
@echo_lovely said in Qt5 how to catch an exception?:
or how do I turn on the switch of Qt5 and catch the exception?
As written before, Qt does NOT use exception, for historical reason, and prefer use return code values to handle errors.
There is an effort done for "exception safety", take a look at documentation for more details: https://doc.qt.io/qt-5/exceptionsafety.html -
Environment
- OS: Ubuntu 20.04LTS
- Qt-Version: 5.12.8
Problem
How to catch an exception?
if my code likes thistry{ //if here occur an null_pointer_exception or io_exception,how to catch the exception? }catch(???){ ??? }or how do I turn on the switch of Qt5 and catch the exception?
Qt does not forbid to use exceptions in general. You should avoid to use them across signal/slot boundaries unless you are certain about what you are doing. With a direct connection exceptions across signal/slot boundaries would work as these are regular function calls internally. If signals are queued inside the event loop chaos will happen. You need to wrap the
exec()into atry/catch. There is also no safe way to recover the event loop.You don't always have a choice if exceptions are used, especially with 3rd party libraries. Here, you have to make sure to catch all exceptions before emitting a signal. Then you are safe. This is also just plain old C++.