Ivan
Ivan

Reputation: 20101

Recommended error handling (try/catch or exceptions) using Pyside/Qt

I'm developing an Pyside/Qt application, coming from a scientific background. What is the best practices for try/catch errors in Pyside? For example, having several QCheckBox, what is the best approach for handling an error if none of the boxes is checked?

Thanks

EDIT: Thanks for the comments. I'm looking for some suggestions on what is the best approach in code when user input is being considered. An example:

        if self.main_frame.LRadioButton.isChecked():

            if self.main_frame.RadioButton2.isChecked():
                print 'clicked'
            else:
                print 'no button selected!'

        elif self.main_frame.TRadioButton.isChecked():

            if self.main_frame.RadioButton3.isChecked():

                print 'clicked'
            else:
                print 'No button selected!'
        else:
            print 'no button selected, top level'

So there are possibilities that the user will try to do further action without having selected at least one of the possibilities given by the program. What should be done to handle the "no button selected" parts? Throw an exception? Catch all the events by hand?

Hope that now is clear.

Thanks again!

Upvotes: 1

Views: 1643

Answers (1)

aquavitae
aquavitae

Reputation: 19154

Assuming I understand your question...

Generally it is not a good idea to throw exceptions because the user didn't check the right box. Better practice would be, for example, to pop up a message box asking the user to re-enter the information. This means looking at what's been entered and checking if its valid (according to whatever rules you apply). However, python is fairly robust when it comes to exceptions. A nan won't result in a crash and burn, it will just cause an exception to be thrown, a traceback will be printed and control will return to your application.

In short, don't throw exceptions because the user entered something wrong. Rather, check the input and respond to it appropriately. E.g.:

while denominator == 0:
    QMessageBox('Invalid values (probably denominator). Please re-enter')
result = numerator / denominator

Note that trapping an exception might be the easiest way of doing this if checking it is too complicated:

while not can_continue:
    try:
        result = complex_maths_involving_division(a, b, c)
    except ZeroDivisionError:
        QMessageBox('Invalid values resulting in zero division. Please re-enter')
    else:
        can_continue = True

Upvotes: 1

Related Questions