#Wei Liu
#11/15/2021
#U3M3A3.1
#We are learning about Error Handling
lst = [0, 1, 2]
print(lst[30])
IndexError: list index out of range
# x is not defined anywhere
print(x)
-3
s1 = 'Word1'
s2 = 'Word2'
s1/s2
TypeError: unsupported operand type(s) for /: 'str' and 'str'
# [ ] Write an expression to raise a `ModuleNotFoundError` exception
import cristal
ModuleNotFoundError: No module named 'cristal'
# [ ] Write an expression to raise an `ImportError` exception
from math import datetime
ImportError: cannot import name 'datetime' from 'math' (/usr/local/lib/python3.7/lib-dynload/math.cpython-37m-x86_64-linux-gnu.so)
try:
5/0
except ZeroDivisionError:
print("Cannot divide by zero!")
print("Program is still running")
Cannot divide by zero!
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")
Cannot divide strings
5.0
print executed
6.0
print executed
Cannot access out of range elements
Cannot access out of range elements
# Without handling unexpected exception
x = [5]
try:
x / 0
except ZeroDivisionError:
print("Cannot divide by zero!")
TypeError: unsupported operand type(s) for /: 'list' and 'int'
# Handling unexpected exception
x = [5]
try:
x / 0
except ZeroDivisionError:
print("Cannot divide by zero!")
except:
print("Unexpected error")
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)
List appended with 2.0
Cannot divide 12 by <class 'str'>
Cannot divide 12 by <class 'list'>
Cannot divide by 0
List appended with 4.0
Unexpected error: list index out of range
The new list is: [2.0, 4.0]
# Without exception handling
from math import sqrt
x = -3
sqrt(x)
ValueError: math domain error
# 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)
math domain error
# [ ] 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!")
1
11
Cannot do: <class 'int'> + <class 'list'>
Cannot do: <class 'list'> + <class 'str'>
hellogoodbye
Index out of range
Index out of range
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!")
4 / 2 = 2.00
Done!
x = 3
y = 2
try:
print(x/y)
except ZeroDivisionError:
print("Cannot divide by zero")
else:
print("All good! No exceptions were raised.")
1.5
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")
1.5
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")
Cannot divide by zero
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")
No exceptions were raised, you can use y = 12.0
# [ ] 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")
# Close the file (will not be reached if an exception was raised)
f.close()
print("File closed")
FileNotFoundError: [Errno 2] No such file or directory: 'parent_dir/text_file.txt'
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))
The number is outside of the acceptable range
The number is outside of the acceptable range
invalid literal for int() with base 10: 'cri'
5 was accepted
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))
4 was accepted
# [ ] 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 vaild")
valid = True
except ValueError as except_object:
print("{}".format(except_object))
print("{:d} was accepted".format(x))
5 was accepted
# [ ] 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 vaild")
else:
return num
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))
45 was accepted