The try and except are two blocks of code where the try block lets you test a block of code for errors and except block lets, you handle the error. Sometimes during the script execution if an error occurs (exception) Python will stop the script execution and generate an error message. These exceptions are handled using except statement. The general form of the try and except code block is given below.
Example 1 Create a program which will print the variable a using try-except block of code.
Solution: As previously defined we use try statement to test a block of code and if any exception occurs it should be handeled by except block. Inside the try statement we will place print(a) command and inside the except statement we will palce the print("Exception occured.").
Example 2 Create a program using try and except block which will ask a user to type in a number which will be multiplied by 2 and print the result. In case the variable containing a number is not declared the program must have exception for NameError and exception for TypeError in case the variable contains string which could not be converted to a float.
Solution: The purpose of this example is to create two except statements which will handle 2 types of errors NameError and ValueError. The first code line that will be created inside the try statement is to ask the user to type "y" if he wants to enter a number and "n" if he doesn't want to enter a number. The choice made by the user ('y'/'n') will be assigned to a variable named USER_INPUT1. If the USER_INPUT1 is equal to "y" it will ask a user again to type the number and this number will be assigned to a variable USER_INPUT2. This variable will then be converted to a float type and assigned to variable x. On the other hand, if the value of the USER_INPUT1 is equal to "n" then the else statement will be processed which has a pass function inside the else statement. Finally the solution will be printed out in form "2*{} = {}".format(x, 2*x). The entire code of the try statement is given below.
Example 3 Create a program that will ask a user to write the mass value that can be converted to grams using the try-except-finally method.
Solution: In the try block we will ask a user to type in a number. This number will be converted to a float later but for now, it will be assigned to the variable name USER_INPUT. Next, we will see if the USER_INPUT value is equal to quit and if it is equal to quit the program will show the message "Program terminated". If on the other hand the number is entered it will be converted to float and multiplied by 1000 to convert it from kilograms to grams. This value will be assigned to variable named result. and the value will be displayed as output using the print function. If for some reason any combination of characters is typed and is not equal to "quit" the ValueError will be raised and the message "Enter another value" will be displayed. At the end we will type a finally statement which will always print (No matter the program outcome) the message "Type 'quit' to exit the program." The entire program code is given below.
try:The name of the specific exception raised by Python can be written after the except keyword. There can be many except blocks defined i.e. if you want to execute a specific block code for a special raised exception (error). Besides the try and except block you can add the else block and finally block to your code. The else block lets you to execute the code when there is no error and the finally block lets you execute code, regardless of the result of the try-except blocks.
#Try Block
except ErrorName:
#Except block
Example 1 Create a program which will print the variable a using try-except block of code.
Solution: As previously defined we use try statement to test a block of code and if any exception occurs it should be handeled by except block. Inside the try statement we will place print(a) command and inside the except statement we will palce the print("Exception occured.").
try:The output is given below.
print(a)
except:
print("Exception occured.")
Exception occured.The reason why the output is "Exception occurred." is because the variable a is not defined. If we try to show the output of the print(a) command without using the try-except block of code Python would raise NameError: name 'a' is not defined.
Example 2 Create a program using try and except block which will ask a user to type in a number which will be multiplied by 2 and print the result. In case the variable containing a number is not declared the program must have exception for NameError and exception for TypeError in case the variable contains string which could not be converted to a float.
Solution: The purpose of this example is to create two except statements which will handle 2 types of errors NameError and ValueError. The first code line that will be created inside the try statement is to ask the user to type "y" if he wants to enter a number and "n" if he doesn't want to enter a number. The choice made by the user ('y'/'n') will be assigned to a variable named USER_INPUT1. If the USER_INPUT1 is equal to "y" it will ask a user again to type the number and this number will be assigned to a variable USER_INPUT2. This variable will then be converted to a float type and assigned to variable x. On the other hand, if the value of the USER_INPUT1 is equal to "n" then the else statement will be processed which has a pass function inside the else statement. Finally the solution will be printed out in form "2*{} = {}".format(x, 2*x). The entire code of the try statement is given below.
try:As you can see in the previous code block two types of errors can occur. The first type of error is the NameError which will be raised by Python if the x variable is not defined. This error can be raised if we choose not to enter a number. The second error is TypeError which will be raised by Python if we type a string instead of the number and assign it to the variable USER_INPUT2. These two exceptions will be handled by creating two except statements where one will be except NameError and the second except Type Error.
USER_INPUT1 = input("Do you want to enter a number. 'y/n'")
if USER_INPUT1 == 'y':
USER_INPUT2 = input("Enter a number:> ")
x = float(USER_INPUT2)
else:
pass
print("2*{} = {}".format(x,2*x))
except NameError:The entire code of Example 2 is given below.
print("NameError occured since variable x is not defined.")
except ValueError:
print("ValueError occured -> String could not be converted to float.")
try:To test the program we will type 'n' when the program asks us to "Do you want to enter a number." which will in the end raise NameError.
USER_INPUT1 = input("Do you want to enter a number. 'y/n'")
if USER_INPUT1 == 'y':
USER_INPUT2 = input("Enter a number:> ")
x = float(USER_INPUT2)
else:
pass
print("2*{} = {}".format(x,2*x))
except NameError:
print("NameError occured since variable x is not defined.")
except ValueError:
print("ValueError occured -> String could not be converted to float.")
Do you want to enter a number. 'y/n' nNow we are going to raise ValueError. This will be done by typing a bunch of characters that cannot be converted to a float.
NameError occurred since variable x is not defined.
Do you want to enter a number. 'y/n' yFinally, we are going to type 20 which will be eventually shown as output without raising any exceptions.
Enter a number:> afgadfh
ValueError occurred -> String could not be converted to float.")
Do you want to enter a number. 'y/n' y
Enter a number:> 20
2*20 = 40
Example 3 Create a program that will ask a user to write the mass value that can be converted to grams using the try-except-finally method.
Solution: In the try block we will ask a user to type in a number. This number will be converted to a float later but for now, it will be assigned to the variable name USER_INPUT. Next, we will see if the USER_INPUT value is equal to quit and if it is equal to quit the program will show the message "Program terminated". If on the other hand the number is entered it will be converted to float and multiplied by 1000 to convert it from kilograms to grams. This value will be assigned to variable named result. and the value will be displayed as output using the print function. If for some reason any combination of characters is typed and is not equal to "quit" the ValueError will be raised and the message "Enter another value" will be displayed. At the end we will type a finally statement which will always print (No matter the program outcome) the message "Type 'quit' to exit the program." The entire program code is given below.
try:Output:
USER_INPUT = input("Enter a mass value:> ")
if USER_INPUT == "quit":
print("Program terminated")
result = float(USER_INPUT)*1000
print("m = {}[kg]*1000[g/kg] = {} [g]".format(USER_INPUT,result))
except ValueError:
print("Enter another value.")
finally:
print("Type 'quit' to exit the program.")
Enter a mass value:> 30
m = 30[kg]*1000[g/kg] = 30000.0 [g]
Type 'quit' to exit the program.