Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases now! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Pyside GUI Application Development- Second Edition

You're reading from   Pyside GUI Application Development- Second Edition Develop more dynamic and robust GUI applications using PySide, an open source cross-platform UI framework

Arrow left icon
Product type Paperback
Published in Jan 2016
Publisher Packt
ISBN-13 9781785282454
Length 144 pages
Edition 2nd Edition
Languages
Tools
Arrow right icon
Authors (2):
Arrow left icon
Venkateshwaran Loganathan Venkateshwaran Loganathan
Author Profile Icon Venkateshwaran Loganathan
Venkateshwaran Loganathan
Gopinath Jaganmohan Gopinath Jaganmohan
Author Profile Icon Gopinath Jaganmohan
Gopinath Jaganmohan
Arrow right icon
View More author details
Toc

Exception handling as a practice

It is not always possible to foresee all the errors in your programs and deal with them. Python comes with an excellent feature called exception handling to deal with all runtime errors. The aim of the book is not to explain this feature in detail but to give you some basic ideas so that you can implement it in the code that you write.

In general, the exceptions that are captured while executing a program are handled by saving the current state of the execution in a predefined place and switching the execution to a specific subroutine known as exception handler. Once they are handled successfully, the program takes the normal execution flow using the saved information. Sometimes, the normal flow may be hindered due to some exceptions that could not be resolved transparently. In any case, exception handling provides a mechanism for smooth flow of the program altogether.

In Python, the exception handling is carried out in a set of try and except statements. The try statements consist of a set of suspicious code that we think may cause an exception. On hitting an exception, the statement control is transferred to the except block where we can have a set of statements that handles the exception and resolves it for a normal execution of a program. The syntax for the same is as follows:

  try : suite
  except exception <, target> : suite
  except : suite

Here, suite is an indented block of statements. We can also have a set of try, except block in a try suite. The former except statement provides a specific exception class that can be matched with the exception that is raised. The latter except statement is a general clause that is used to handle a catch-all version. It is always advisable to write our code in the exception encapsulation.

In the previous example, consider that we have missed instantiating the appLabel object. This might cause an exception confronting to a class of exception called NameError. If we did not encapsulate our code within the try block, this raises a runtime error. However, if we had put our code in a try block, an exception can be raised and handled separately, which will not cause any hindrance to the normal execution of the program. The following set of code explains this with the possible output:

# Import the necessary modules required
import sys
from PySide.QtCore import *
from PySide.QtGui import *

# Main Function
if __name__ == '__main__':

    # Create the main application
    myApp = QApplication(sys.argv)

    # Create a Label and set its properties
    try:
        #appLabel = QLabel()
        appLabel.setText("Hello, World!!!\n Look at my first app using PySide")
        appLabel.setAlignment(Qt.AlignCenter)
        appLabel.setWindowTitle("My First Application")
        appLabel.setGeometry(300, 300, 250, 175)

        # Show the Label
        appLabel.show()

        # Execute the Application and Exit
        myApp.exec_()
        sys.exit()
    except NameError:
        print("Name Error:", sys.exc_info()[1])
        pass

In the preceding program, if we did not handle the exceptions, the output would be as shown in the figure:

Exception handling as a practice

Conversely, if we execute the preceding code, we will not run into any of the errors shown in the preceding figure. Instead, we will have captured the exception and given some information about it to the user, as follows:

Exception handling as a practice

Hence, it is always advised to implement exception handling as a good practice in your code.

lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime