Python

Exception Handling in Python

Exception Handling in Python
When we run any code that contains error then the error displays in the output by stopping the execution of the program. Some errors may not be recognized by the users and create an undesirable situation for them. But if the error can be displayed in an understandable format for the users then it is easy for them to know the reason for the error. In any object-oriented programming, try-catch or try-catch-finally block is used to handle errors and display them in a readable format which is called exception handling. How exception handling can be done in Python script is shown in this tutorial.

Syntax :

try:
block…
except Exception:
handler…
else:
block…
finally:
block…

Here, if any error occurs while executing the statements of try block then an exception will be generated and throw the error to the corresponding except handler. Multiple errors can be generated in a single try block and then you have to write multiple except handlers.  The statements of the else block will be executed if no error occurs in the try block. The statements of the finally block will be executed if any error occurs or not occurs. For exception handling, using else and finally blocks are not essential. Different types of exception handling in python are explained in the next part of the tutorial.

Example-1: Use of a single try-except block to validate numeric data:

This example shows the very simple use of exception handling in Python. In the try block, two inputs will be taken from the user, one is a string value and another is a numeric value.  If the user types any string value in place of numeric value for the second input then, the ValueError exception will be generated by python3 and a custom error message will be displayed from except block.

#!/usr/bin/env python3
# Define the try block
try:
# Take any data as a string
name = input("Enter your name: \n")
# Take any numeric data
age = int(input("Enter your age: \n"))
# Print the formatted data with name and age
print("Hello %s, You are %s years old." %(name, age))
# handle input errors
except (ValueError):
# Print custom error message
print("Wrong input! You have to type a number as your age.")

Output:

The script is executed two times in the following output with the wrong input and correct input. The first time, when the user type 'Thirty one' as age value for the second input that takes numeric value then a ValueError is generated and the error message is displayed from the except block. The second time, no error is generated for correct input values.

Example-2: Use of multiple except block to handle multiple errors:

How you can use multiple except block to handle multiple errors is shown in this example.  Two types of errors will be handled in this script. A filename is taken as input from the user for reading. If the file does not exist then it will generate an IOError exception and if the file exists but empty then it will raise a custom exception. For this, two except blocks are used in this script. When none of the error occurs then the content of the file will be displayed.

#!/usr/bin/env python3
# Import os module
import os
# Define the try block
try:
# Take the filename as input
filename = input('Enter a filename\n')
# Open the file for reading
file_handler = open(filename)
# Set the seek ponter from 0 to end of the file
file_handler.seek(0, os.SEEK_END)
# Read the size of the file in bytes
size = file_handler.tell()
# Print the file content and the number of characters of the file
if(size > 0):
# Set the ponter to the starting of the file
file_handler.seek(0)
# Read and store the content of the file in a variable
file_content = file_handler.read()
print("\nThe content of the file given below\n")
print(file_content)
print("The size of the file is %d bytes"  %size)
else:
# Raise exception if the file is empty
raise Exception('The file has no content.')
# Print the error message if the file does not exist
except IOError as error:
print(error)
# Print the error message if the file is empty
except Exception as e:
print('Error:%s' %e)
# Print the message if there is no error
else:
print('No error occurs')

Output:

The script is executed for three times. The first time, a filename is given that does not exist and the output shows an IOError message. The second time, a filename is given that exist but has no content and the output shows a custom message. The third time, a filename is given that exists and contains text. The output shows the content of the file.

Example-3: Use of try-except-finally block to handle division error

The example shows the use of a try-except-finally block to handle division error. Two numeric values will be taken as input and divide the first input by second input in the try block. Two types of errors can occur here. One is ValueError when the user will type any value without number and another is ZeroDivisionError when the user will take 0 as a second input.

#!/usr/bin/env python3
# Define the try block
try:
# Enter two float numbers
n1 = float(input('Enter a number\n'))
n2 = float(input('Enter a number\n'))
# Divide these numbers
division = n1 / n2
# Handle errors
except (ZeroDivisionError, ValueError):
print("Divided by zero error or The value is not a number")
# Print message if no error occurs
else:
print("The result of the division is %f" %division )
# Print message if an error occurs or not occurs
finally:
print("The end")

Output:

Here, the script is run for two times with both correct inputs and with the second input as 0. So, the second time exception is generated and displays the error message.

Conclusion:

This tutorial shows the basic exception handling process in python3 for the new python users. The readers will be able to understand what is exception handling and how to apply in python script after practicing the above examples.

Як встановити League of Legends на Ubuntu 14.04
Якщо ви шанувальник League of Legends, то це можливість для вас тестувати League of Legends. Зверніть увагу, що LOL підтримується на PlayOnLinux, якщо...
Встановіть останню стратегічну гру OpenRA на Ubuntu Linux
OpenRA - це ігровий движок Libre / Free Real Time Strategy, який відтворює ранні ігри Вествуда, такі як класичний Command & Conquer: Red Alert. Пошире...
Встановіть найновіший емулятор Dolphin для Gamecube & Wii на Linux
Емулятор Dolphin дозволяє грати у вибрані вами ігри Gamecube та Wii на персональних комп’ютерах Linux (ПК). Будучи вільно доступним і відкритим ігров...