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:
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:
Hence, it is always advised to implement exception handling as a good practice in your code.