alphanumeric
alphanumeric

Reputation: 19329

How to get the exception and to display the warning

The code posted below creates a single dialog with a label and a button. Pressing button calls calculate function that raises ZeroDivisionError exception.

How to rewrite the code so dialog runs after calculate raises an exception. dialog would then set label to warning message.

app = QApplication([])

def divide():
    return 1 / 0

class Dialog(QDialog):
    def __init__(self, parent=None):
        super(Dialog, self).__init__(parent)
        self.setLayout(QVBoxLayout())
        self.label = QLabel('Please press the button')
        button = QPushButton('Calculate')   
        button.clicked.connect(self.onClick)
        self.layout().addWidget(self.label)
        self.layout().addWidget(button)
        self.show()

    def onClick(self, text):
        divide()

dialog = Dialog()
app.exec_()

Upvotes: 0

Views: 1816

Answers (2)

John R
John R

Reputation: 1508

Use try/except.

def onClick(self, text):
    try:
        divide()
    except Exception, e:
        print(e.massage)

Or replace

print(e.massage)

With whatever you want to do on exception/error.

If you want to only catch this specific type of error, use:

def onClick(self, text):
    try:
        divide()
    except ZeroDivisionError, e:
        print(e.massage)

Upvotes: 0

Xatyrian
Xatyrian

Reputation: 1384

What if you intercept the exception in onClick ? I am no expert in PyQt5 but I guess you can do something like:

class Dialog(QDialog):
    def __init__(self, parent=None):
        super(Dialog, self).__init__(parent)
        self.setLayout(QVBoxLayout())
        self.label = QLabel('Please press the button')
        button = QPushButton('Calculate')   
        button.clicked.connect(self.onClick)
        self.layout().addWidget(self.label)
        self.layout().addWidget(button)
        self.show()

    def onClick(self, text):
        try:
            divide()
        except ZeroDivisionError:
            self.label.setText("Error: there was a division by zero")

Intercepting the exception directly inside the divide method would be a bad idea in my opinion

Upvotes: 2

Related Questions