8) c. Raising Exceptions Examples




Kanan is a student in high school who is fascinated in the circle of life. According to a book he studied he assumes a person has 4 stages of life. 0-25: 1st, 26-50:: 2nd, 51-75: 3rd and 76-100: 4th. He has written the whole program and want to fail the code if the age is less than 0 and greater than 100 years. Write a code for him such that an exception is raised in both of these scenarios.

1
2
3
4
Output:
Enter the age
 552
ValueError: This is not the correct age for calculating the stages on line 17




Ruby is a Windows expert and thinks that it is the greatest OS ever created. She has created a python program that can be run on windows system only. Ruby has the whole code ready with her and wants to assert that the OS is windows else fail the program giving the exception: “Only Windows machines to be used”. Create the assertion for her.

1
2
3
4
5
6
7
Program:
#windows.py
import platform
def assert_windows():
    assert 'windows' == platform.system().lower(), "Only Windows machines to be used"

assert_windows()




Jenna is a mathmetician who is known to create super complex formulas. In one of the submodule, she is returning the average of some numbers but the average fails whenever no items are given to this method. She wants the system to be full proof and wants this bug to go away. As she is your friend you want to help her in this and want to raise an exception. Write the code to help her.

1
ValueError: No values provided on line 4




Arachno is a chemist in Neverland. He gets a lot of customers in a day and at the end of the day he enters the name of patients into a system. This helps him know which patients are critical by looking at the medicines that they have been prescibed and also get a history of those patients. He is tired from all the work at the end of the day and thus can enter digits in names. Write a program that raises a ValueError whener a name has digits..

1
2
3
4
Output:
Enter the name of patient
 c3po
ValueError: The name has digits. Exiting. on line 6




Dewey is a biologist who is orking on DNA sequencing. She is a researcher and checks how does DNA transfer from one generation to another. As a part of her job she also wants to check if the DNA sequence entered is a valid DNA sequence or not. She already has the code ready to do the processing but wants to write the DNA Validator. Write the code for her that raises an exception whenever DNA sequence is not valid. Please note that DNA sequence only consists of A,C,T and G nucleotide bases.

1
2
3
4
Program:
Enter the DNA sequence
 ATNG
ValueError: DNA sequence not valid on line 5