#Kieran Belcher
#November 16, 2021
#U3M3A3.1
#Error Handling
lst = [0, 1, 2]
print(lst[30])
# x is not defined anywhere
print(x)
s1 = 'Word1'
s2 = 'Word2'
s1/s2
# [ ] Write an expression to raise a `ModuleNotFoundError` exception
import aarg
# [ ] Write an expression to raise an `ImportError` exception
from math import datetime
try:
5/0
except ZeroDivisionError:
print("Cannot divide by zero!")
print("Program is still running")
lst = ['text', 5, 12]
for i in range(5):
try:
print(lst[i] / i)
print("print executed")
except TypeError:
print("Cannot divide strings")
except IndexError:
print("Cannot access out of range elements")
# Without handling unexpected exception
x = [5]
try:
x / 0
except ZeroDivisionError:
print("Cannot divide by zero!")
# Handling unexpected exception
x = [5]
try:
x / 0
except ZeroDivisionError:
print("Cannot divide by zero!")
except:
print("Unexpected error")
old_lst = [6, 'word', [2, 5], 0, 3]
new_lst = []
for i in range(6):
try:
tmp = 12 / old_lst[i]
new_lst.append(tmp)
print("List appended with", tmp)
except TypeError:
print("Cannot divide {0:d} by {1:}".format(12, type(old_lst[i])))
except ZeroDivisionError:
print("Cannot divide by 0")
# Handling unexpected exceptions, by showing the associated error message
except Exception as exception_object:
print("Unexpected error: {0:}".format(exception_object))
print()
print("The new list is:", new_lst)
# Without exception handling
from math import sqrt
x = -3
sqrt(x)
# With exception handling
from math import sqrt
x = -3
try:
sqrt(x)
except ValueError as exception_object: # Storing the error message in exception_object
print(exception_object)
# [ ] The following program adds `lst1` to `lst2` element by element
# Find all exceptions that will be generated by this program,
# then handle the exceptions by displaying meaningful messages.
# You should also handle unexpected exceptions.
lst1 = [-4, -5, 6, [6], "hello"]
lst2 = [ 5, 16, [6], "hello", "goodbye"]
for i in range(7):
try:
print(lst1[i] + lst2[i])
except TypeError:
print("cannot do: {} + {}".format(type(lst1[i]),type(lst2[i])))
except IndexError:
print("Index out of range")
except Exception as exception_object:
print(exception_object)
print("Done!")
# [ ] The following program asks the user for an integer then prints the result of dividing it by 2.
# If the user enters an invalid value (i.e. "4.3" or "Hello"), the program terminates.
# Use exception handling to deal with unexpected user input and display a meaningful message.
x = input("Enter an integer: ")
try:
x = int(x)
print("{:d} / 2 = {:.2f}".format(x, x / 2))
except Exception as exception_object:
print(exception_object)
print("Done!")
x = 3
y = 2
try:
print(x/y)
except ZeroDivisionError:
print("Cannot divide by zero")
else:
print("All good! No exceptions were raised.")
x = 3
y = 2
try:
print(x/y)
except ZeroDivisionError:
print("Cannot divide by zero")
finally:
print("Code that will run whether an exception was raised or not")
x = 3
y = 0
try:
print(x/y)
except ZeroDivisionError:
print("Cannot divide by zero")
finally:
print("Code that will run whether an exception was raised or not")
# [ ] The following program asks the user for an integer `x` then assigns `y` as the result of dividing `x` by 2.
# If the user enters an invalid value (i.e. "4.3" or "Hello"), the program terminates.
# Use exception handling to deal with unexpected user inputs, then use an `else` clause to calculate the value of `y`.
x = input("Enter an integer: ")
y = None
try:
x = int(x)
except Exception as exception_object:
print(exception_object)
else:
y = x / 2;
if y is not None:
print("No exceptions were raised, you can use y =", y)
else:
print("An exception was raised, y cannot be used")
# [ ] The following program tries to write to a file opened for reading.
# The program will terminate before closing the file, and the file resources will not be released.
# Use exception handling with a `finally` clause to make sure the file is closed.
# Open a text file for reading
f = open("parent_dir/text_file.txt", 'r')
# Try to write to a file open for reading (will raise an exception)
f.write("This string will not be written")
except Exception as exception_object:
print(exception_object)
# Close the file (will not be reached if an exception was raised)
f.close()
print("File closed")
valid = False
while not valid:
try:
x = int(input("Enter a number between 1 and 10: "))
if ((x < 1) or (x > 10)):
raise ValueError("The number is outside of the acceptable range")
valid = True
except ValueError as except_object:
print("{}".format(except_object))
print("{:d} was accepted".format(x))
def isValid(num):
if ((num < 1) or (num > 10)):
raise ValueError("The number is outside of the acceptable range")
else:
return num
valid = False
while not valid:
try:
x = int(input("Enter a number between 1 and 10: "))
x = isValid(x)
valid = True
except ValueError as except_object:
print("{}".format(except_object))
print("{:d} was accepted".format(x))
# [ ] Write a program to keep prompting the user for an odd positive number until a valid number is entered.
# Your program should raise an exception with an appropriate message if the input is not valid.
valid = False
while not valid:
try:
x = int(input("enter an odd positive number: "))
if ((x < 0) or (x % 2 == 0)):
raise ValueError("number is not valid")
valid = True
except ValueError as except_object:
print("{}".format(except_object))
print("{:d} was accepted".format(x))
# [ ] Complete the function `isValid` to test the validity of a user input. A valid input should be an odd positive integer.
# The function should raise an exception with an appropriate message if the input is not valid.
# The function need not handle the exception.
def isValid(num):
if ((x < 0) or (x % 2 == 0)):
raise ValueError("number is not valid")
else:
return num
pass
valid = False
while not valid:
try:
x = int(input("Enter an odd positive number: "))
x = isValid(x)
valid = True
except ValueError as except_object:
print("{}".format(except_object))
print("{:d} was accepted".format(x))