When a Python program find an error, it stops the execution and throw an error message. This error is called exception. An exception generally points towards an irregular event or problem that occurs during the execution of a program. If there is no countermeasures available to handle these exceptions, Python stops whatever it is doing and displays an error message detailing the exception.
This simple example will show you that how Python raises an exception:
Figure 1: Displaying an exception in Python
As we can see in Figure 1, when Python tries to covert string “Hi !” to a floating type number, it raises an exception, because string to float conversion is not allowed in Python.
Exception handling enables a user to develop such applications, which can resolve exceptions. Exception handling allows an application to ignore that exception and continue its execution as no problem has been there.
Using a try Statement with an except Clause
In Python, to catch (or trap) an exception, a try statement with an except block is used. To catch an exception, first user should have to identify that potential code that could potentially raise an exception. For example, as in Figure 1, this potential code is where Python tries to unauthorized type conversion. We use try statement to section off this code that can cause an exception at run time. Then, a block of statements are written with except clause. These statements are to be executed only when an exception is raised.
We can understand it using an example program Sample Handle. This program asks the user to enter a number. We check the situation if user inputs a string instead of number and tries to convert it to a floating point number. We have to identify the potential code that can raise an exception and we use try and except to catch any exception that might be encountered during the execution.
Listing 1: Sample Handle program to demonstrate the use of try and except
# Sample Handle # Demonstrates handling exceptions # try/except try: num = float(input("Enter a number: ")) except: print("Something went wrong!")
The output of this program is given below:
Figure 2: Sample Handle Program output window
As we can see in above example, when user inputs a numeric value, no exception is raised. Program skips the except clause, and continues execution, but when we input a string “alok”, an exception is raised. This exception is caught and except clause executes which tell the user that “Something went wrong! “.
Exception Type Specification
As we know, a program can encounter a number of problems during its execution. These different errors result in different type of exceptions. For example, when we try to convert the string “Hi!” to a floating point number, it returns a ValueError exception because the input characters have wrong type(they are not digits).There are more than two dozen of exception types but we list the most common ones in table 1:
|IOError||Raised when an I/O operation fails, such as when an attempt is made to open a non-existent file in read mode.|
|IndexError||Raised when a sequence is indexed with a number of a non-existent element|
|KeyError||Raised when a dictionary key is not found|
|NameError||Raised when a name (of a variable or function, for example) is not found|
|SyntaxError||Raised when encountered a syntax error .|
|TypeError||Raised when a built-in operation or function is applied to an object of inappropriate type.|
|ValueError||Raised when a built-in operation or function receives an argument that has the right type but an inappropriate value.|
|ZeroDivisionError||Raised when the second argument of a division or modulo operation is zero|
The user is facilitated by except clause to specify exactly the type of exceptions, it will handle. If user wants to specify a single exception type, he just has to list the specific type of exception after except.
Now, again we’ll use our previous example program Sample Handle, but this time we specify a specific trap for a ValueError:
Listing 2: Sample Handle Program with specific exception type
# specifying exception type Try: num = float(input("\nEnter a number: ")) except ValueError: print("That was not a number!")
The output of this code is given below:
Figure 3: Output of the modified Sample Handle program
Now because we have defined a specific type of exception in our program, print function will execute only when a ValueError is encountered. As a result, user can be more specific about the error message to be displayed, as in this case, we displays “That was not a number!”. But for any other type of exception, raised in try statement, except cause will not catch the exception and program will be stopped.
It is good programing practice to specify exception types to catch each individual case of exception. Generally, we should avoid the use of simple except clause without specific exception type.
Multiple Exception Type Handling
It is possible that a single piece of code can result multiple types of exception. Fortunately, Python provides us the facility to trap multiple types of exception. We can trap multiple types of exceptions by listing them in a single except clause. These exceptions will form a comma separated group enclosed in a set of parameters:
Listing 3: multiple exception handling
# handle multiple exception types print() for value in (None, "Hi!"): try: print("Attempting to convert", value, "-->", end=" ") print(float(value)) except (TypeError, ValueError): print("Something went wrong!")
The output of this code is shown below:
Figure 4: Multiple Exception catching
In this example, the program tries two different type of values to convert in floating type. Both fail with a different exception type. float(None) will raise a TypeError because the conversion is possible only for numbers and strings. float(“Hi!”) will raise a ValueError because input characters have wrong values(they’re not digits). As a result, both types of exceptions will be handled.
We can use multiple except clause to catch different exceptions too. A user can list as many except clauses as he like, after a single try statement:
Listing 4: Multiple except clause to catch different exceptions
print() for value in (None, "Hi!"): try: print("Attempting to convert", value, "-->", end=" ") print(float(value)) except TypeError: print("I can only convert a string or a number!") except ValueError: print("I can only convert a string of digits!")
The output of this code is displayed below:
Figure 5: Output of program using multiple except clause
Now, because each exception type has his own block, so when value is none, a TypeError is raised with the message "I can only convert a string or a number!". When value is “Hi!”, ValueError will raised and show the string "I can only convert a string of digits!".
So, now we know that exception handling is very important to develop fault tolerant programs, a Python developer must develop the skills to master this topic. This writing should be helpful for those, who just migrated to Python and want some quick hands with exception handling method of Python.
In this article we went through how to handle exceptions in python applications. We have learned the exception handling by using try-except statement. Then we have learned exception type specifications and how to handle multiple type exceptions. A good code always use exception handling properly so that in case of any problem with the code the application does not break and display a helpful message to user. Exception handling ensures the smooth running of the application and in case of any issue it does not lead to application crash.