Glassbox testing
Path-complete testing is not necessarily enough
def abs(x):
""" Assumes x is an int
Returns x if x>=0 and –x otherwise """
if x < -1:
return –x
else:
return x
abs(-1) incorrectly returns -1Debugging
Print statements
Debugging steps
Error messages - easy Consider the following program
test = [1, 2, 3]
test[4] # IndexError
int(test) #TypeError
a #NameError
'3'/4 #TypeError
a = len([1, 2, 3] print(a) #Syntax Error
Logic Errors - Hard
Exceptions and Assertions
test = [1, 7, 4] test[4] # IndexError
int(test) # TypeError
a # NameError
'a'/4 # TypeError
Other examples of exceptions: already seen common datatypes
SyntaxError: Python can't parse programNameError: Local or global name not foundAttributeError: Attribute reference failsTypeError: Operand does not have correct typeValueError: Operand type okay, but value is illegalIOError: IO system reports malfunction (e.g., file not found)Dealing with exceptions
try:
a = int(input("Tell me one number:"))
b = int(input("Tell me another number:"))
print(a/b)
except:
print("Bug in user input.")
except statement.
You can have separate except clauses to deal with a particular type of exception
try:
a = int(input("Tell me one number:"))
b = int(input("Tell me another number:"))
print(a/b)
except ValueError:
print("Could not convert to a number.") # only executes if ValueError comes up
except ZeroDivisionError:
print("Can't divide by zero.") # only executes if ZeroDivisionError comes up
except: # for all other errors
print("Something else went wrong.")
What to do when you encounter an exception?
raise Exception("descriptive string")
Exceptions as control flow
raise keyword can be used to indicate an exception (with its name and
description) at runtime.except block at the very end.raise <exceptionName>(<arguments>)Example:
raise ValueError("something is wrong") #The string description is optional