I can do:
try: # do something that may fail except: # do this if ANYTHING goes wrong
I can also do this:
try: # do something that may fail except IDontLikeYouException: # say please except YouAreTooShortException: # stand on a ladder
Exceptions are raised with a raise keyword.
raise Exception('This is the error message')
raise Exception('This is the error message') #This will return an exception object that is raised
Let's make an function that prints out a box like:
**********
* *
* *
**********
above box is 4*10 stars wide.
The function takes the symbol, width and height and then prints out a box according to it.
def boxPrint(symbol, width, height):
print(symbol * width) #string replication
for i in range(height - 2):
print(symbol + (' ' * (width - 2)) + symbol)
print(symbol * width)
boxPrint('+' , 15, 10)
boxPrint('O' , 15, 2)
Seems like it is working fine, but what if passing instead of one character to the symbol, I accidently passed 2 characters
boxPrint('**' , 15, 4)
Then this starts to mess up. The program hasn't crashed, but clearly this is a bug.
Rewriting the program to handle this scenario.
def boxPrint(symbol, width, height):
if len(symbol) != 1:
raise Exception("'Symbol' needs to be a string of length 1")
print(symbol * width) #string replication
for i in range(height - 2):
print(symbol + (' ' * (width - 2)) + symbol)
print(symbol * width)
boxPrint('**' , 5, 4)
boxPrint('*' , 1, 1)
def boxPrint(symbol, width, height):
if len(symbol) != 1:
raise Exception("'Symbol' needs to be a string of length 1")
if (width < 2) or (height < 2):
raise Exception("'width' and 'height' must be greater or equal to 2")
print(symbol * width) #string replication
for i in range(height - 2):
print(symbol + (' ' * (width - 2)) + symbol)
print(symbol * width)
boxPrint('*' , 1, 1)
The entire error message is called a 'Traceback'. It has information about the line that raised the exception.
The text as a string value can be obtained by traceback.format_exc() function.
import traceback
try:
raise Exception('ErrorMessage')
except:
errorFile = open('F:\\pythoncodes\\error_log.txt', 'a') #opening file in append mode
errorFile.write(traceback.format_exc())
errorFile.close()
print('The traceback info was written to error_log.txt')
file = open('F:\\pythoncodes\\error_log.txt')
content = file.read()
print(content)
file.close()
An Assertion is a sanity check that makes sure the code isn't doing something obviously wrong. These checks are performed by assert statements. If they fail, an AssertionError Exception is raised.
assert condition, 'Assert Message'
Assert statements raises assertion error when the condition is false
assert False, 'This is the error message'
Taking an example with a simple traffic simulator program.
market_2nd = {'ns' : 'green', 'ew' : 'red'}
def SwitchLights(intersection):
for key in intersection.keys():
if intersection[key] == 'green':
intersection[key] = 'yellow'
elif intersection[key] == 'yellow':
intersection[key] = 'red'
elif intersection[key] == 'red':
intersection[key] = 'green'
SwitchLights(market_2nd)
But we quickly realised that our virtual cars crashing into each other.
Why did it happen?
market_2nd = {'ns' : 'green', 'ew' : 'red'}
def SwitchLights(intersection):
for key in intersection.keys():
if intersection[key] == 'green':
intersection[key] = 'yellow'
elif intersection[key] == 'yellow':
intersection[key] = 'red'
elif intersection[key] == 'red':
intersection[key] = 'green'
print(market_2nd)
SwitchLights(market_2nd)
print(market_2nd)
In second case the traffic is going in both north-south and east-west direction!
Making an assert statement to overcome this dangerous bug
market_2nd = {'ns' : 'green', 'ew' : 'red'}
def SwitchLights(intersection):
for key in intersection.keys():
if intersection[key] == 'green':
intersection[key] = 'yellow'
elif intersection[key] == 'yellow':
intersection[key] = 'red'
elif intersection[key] == 'red':
intersection[key] = 'green'
assert 'red' in intersection.values(), 'Neither light is red!' + str(intersection)
print(market_2nd)
SwitchLights(market_2nd)
print(market_2nd)
You shouldn't do an except with assert. If the assert fails, your program crashes.
This will reduce the amount of code check to find out the bugs. Assert are for programmer errors, not a user errors