#Conner Kahn
#11/28
#I learend about errors and how to handle them
#I had trouble with the final problem
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
try:
import meth
except ModuleNotFoundError:
import math
# [ ] Write an expression to raise an `ImportError` exception
try:
from datetime import math
except ImportError:
import math
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 add these 2 types together:", lst1[i], "and", lst2[i])
except IndexError:
break
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 ValueError:
print("sorry this is an invalid value:", x)
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)
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")
except ValueError:
print("invalid value")
# [ ] 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.
#create the text file in whatever directory you are in
f = open("text_file.txt", 'w')
f.close()
# Open a text file for reading
# This open will work after the code above opens text_file.txt as 'w'
f = open("text_file.txt", 'r')
try:
# Try to write to a file open for reading (will raise an exception)
f.write("This string will not be written")
except:
print("unexpected error")
finally:
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.
x = 0
while x%2 == 0:
x = input("Please input an integer")
try:
x = int(x)
if x%2 == 0:
print("sorry the value", x, "cannot be accepted")
except ValueError:
print("sorry the value", x, "cannot be accepted")
x = 0
except TypeError:
print("sorry that is an incorrect data type, you entered a", type(x), "this takes an integer")
x = 0
# [ ] 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 (num > 0) and num %2 != 0 :
return num
else:
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))
try:
print("{:d} was accepted".format(x))
except TypeError:
print(x, "is not valid")