0

I am using Qt5.13.0 framework on centos with GCC compiler, try catch is working on windows but no working on Centos.

int main(int argc, char *argv[]) {
  QApplication a(argc, argv);
  a.setStyleSheet(Utils::loadStyle());

 try {
    MainWindow *w = nullptr;
    w->show();

  } catch (...) {
    qWarning() << "Exception handled";
  }

  return a.exec();
}

I want to caught nullptr exception but app crash with code segment fault.

  • 2
    There are no nullptr exceptions in C++. Dereferencing a null pointer results in undefined behavior. When this happens it is too late to do anything about it. What do you want to do when you recognize the null pointer dereference? Instead fix the program so there is no null pointer dereference. – user17732522 Apr 07 '22 at 04:25
  • 1
    Also, `w->show();` is not a null pointer dereference. It dereferences an _indeterminate value_ (which is also undefined behavior). – user17732522 Apr 07 '22 at 04:29
  • Thanks for the quick response, its just an example for nullptr. In windows when Iran this same example I see the catch block ran and print the exception handled and program continue to work but on Centos the program is crashed. – Safdar Sikander Apr 07 '22 at 04:37
  • I update the example not its pointing to nullptr and try to call a function on nullptr. – Safdar Sikander Apr 07 '22 at 04:38
  • The behaviour of the program is undefined. Undefined behaviour means anything can happen. Both an exception and a crash fall under the umbrella of anything. – n. m. could be an AI Apr 07 '22 at 04:45
  • 1
    In Windows these are not C++ exceptions, but [structured exceptions](https://learn.microsoft.com/en-us/cpp/cpp/structured-exception-handling-c-cpp?view=msvc-170), a Windows-specific language extension and even then I think there is no guarantee that the compiler will not just miscompile UB instead of generating the exception. It is not possible to meaningfully handle undefined behavior occurring in C++. Fix your program to not have undefined behavior. – user17732522 Apr 07 '22 at 04:45
  • If you're aiming to log crashes then there are frameworks for doing that, just catching exceptions isn't the right approach – Alan Birtles Apr 07 '22 at 06:04
  • @user17732522, Thanks for the answers, is there any framework or library to catch the error? I want to achieve two things 1. My program crashes randomly after sometime. 2. I want to log the reason why it's crashed. – Safdar Sikander Apr 08 '22 at 04:41
  • @AlanBirtles, Is there any library which logs why my program crashed. – Safdar Sikander Apr 08 '22 at 04:42
  • 1
    @SafdarSikander Maybe you want something like https://stackoverflow.com/questions/77005/how-to-automatically-generate-a-stacktrace-when-my-program-crashes? Or maybe run the program under a debugger in a test environment until the fault occurs. You can also set Linux to generate a core dump if the program crashes. – user17732522 Apr 08 '22 at 04:50

0 Answers0