Exception handling as a practice

It is always not 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 the runtime errors. The aim of the book is not to explain about 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 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 by using the saved information. Sometimes, the normal flow may be hindered due to some exceptions that cannot be resolved transparently. In any case, exception handling provides a mechanism for the 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 consists of a set of suspicious code that we might think cause an exception. On hitting an exception, the statement control is transferred to 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-1, exception-2, ... , exception-n) as target:suite
  except : suite

where 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 which can be matched with exception that is raised. The latter except statement is a general clause which is used to handle the "catch-all" version. It is always advisable to write our code in the exception encapsulation.

In the previous example, consider that we have missed to instantiate the appLabel object. This might cause an exception confronting to a class of exception called "Name Error". If we don't encapsulate our code within the try block, this raises a runtime error. However, if we put our code in a try block, an exception can be raised and handled separately; this will not cause any hindrance to the normal execution of the program. The following 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!!!
 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 don't handle the exceptions, the output would be as shown in the following screenshot:

Exception handling as a practice

However, if we execute the preceding code, we would not run into any errors as shown in the following screenshot. Instead, we could have captured the exception and given some info about it to the user shown as follows:

Exception handling as a practice

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

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.224.56.29