The past weeks, Dan had been covering exceptions but it wasn't quite emphasized on this week's lab. The concepts seemed easy to grasp, but when I work on my exercise, it was quite challenging. Since the exercise is already past the due date, I'll post related code here.
I understand how normally, programs stops on the first error raised, but it is also true that you can mitigate that by using try: . For example:
class E1(Exception):
pass
class E2(Exception):
pass
def raise_errors(x):
try:
int(x)
except ValueError:
raise E1('Raise errors')
finally:
raise E2('because i said so')
raise_errors("now")
The finally clause makes sure the code under it is ran despite the error in try. This code gives 3 errors when you run it. I highlighted the errors below:
Traceback (most recent call last):
File "H:\Libraries\Documents\UTM\CSC148\Exercises\E2\raise_errors.py", line 9, in raise_errors
int(x)
ValueError: invalid literal for int() with base 10: 'now'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "H:\Libraries\Documents\UTM\CSC148\Exercises\E2\raise_errors.py", line 11, in raise_errors
raise E1('Raise errors')
E1: Raise errors
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "H:\Libraries\Documents\UTM\CSC148\Exercises\E2\raise_errors.py", line 16, in <module>
raise_errors("now")
File "H:\Libraries\Documents\UTM\CSC148\Exercises\E2\raise_errors.py", line 13, in raise_errors
raise E2('because i said so')
E2: because i said so
The reason I did this was a misinterpretation of the sentence "Your function reporter must always return normally, so it must catch all exceptions raised while it is executing and must never raise an exception itself". I thought function f is allowed more than one error since it says "catch all exceptions", and so I made this code to try forcing another error.
I posted about this concern I have on discussion board and it appears that function f should not keep going with more errors. Rest assured, I do not need to prepare for such case when I do e2b.py.
To whoever reads my blog: what do you think about this?
No comments:
Post a Comment