Qudpsocket readyread() don't work in try-catch block

213 views Asked by At

I wanna get message by UDP protocol. If I create object to work with QUdpsocket in try-catch block, signal readyread() don't work. But if I created UDPworker's object out of try-catch block - all OK. What I did uncorrect in exceptions and Qt combo? Is it about implementation QUdpsocket?

main.cpp

#include "mainwindow.h"
#include <QApplication>
#include <QtDebug>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    //MyUDP m_UDP; // its work
    
    try
    {
        MyUDP m_UDP; // its not work! WHY?!

    }
    catch(...)
    {
        qDebug()<< "Unknown exception cautch!!!" << endl;
    }

    return a.exec();
}

pr.pro

QT       += core gui network
CONFIG += c++14 console
greaterThan(QT_MAJOR_VERSION, 4): QT += widgets
TARGET = untitled
TEMPLATE = app
DEFINES += QT_DEPRECATED_WARNINGS

SOURCES += \
        main.cpp \
        mainwindow.cpp

HEADERS += \
        mainwindow.h

FORMS += \
        mainwindow.ui

mainwindow.cpp

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QtDebug>
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
}
MainWindow::~MainWindow()
{
    delete ui;
}
MyUDP::MyUDP(QObject *parent) :
    QObject(parent)
{
    socket = new QUdpSocket(this);
    socket->bind(QHostAddress::LocalHost, 6650);
    connect(socket, SIGNAL(readyRead()), this, SLOT(readData()));
}

mainwindow.h

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>

#include <QUdpSocket>
#include <QMessageBox>

namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();

private:
    Ui::MainWindow *ui;
};

//Base class QObject
class MyUDP : public QObject
{
  Q_OBJECT

  public:
      explicit MyUDP(QObject *parent = 0);

      void SayHello();

public slots:
      void readData(){
          QMessageBox::information(0, "Внимание","Это очень важный текст", 0,0,0);
      }

  private:
      QUdpSocket *socket;
};

#endif // MAINWINDOW_H
1

There are 1 answers

0
Pablo Yaggi On BEST ANSWER

You are creating MyUDP inside a try block, not catching any error an getting out of the try/catch scope, so MyUDP is begin destroyed:

try {
        MyUDP m_UDP; // Created in the stack, valid only inside the try block

}
catch (...)
{
}
//m_UDP is already destroyed and undefined here

I should add that you are using QObjects, and signaling/slots mechanism not in intended/orthodox way, but that is beyond your question. You should read the documentation about the QObject and signal/slot mechanism, Qt has plenty of information both on-line and in the QtAssistant application.