0

Does 'raise' executes after all the statements? What is the work flow when we use raise?

try: print(1/0) except: print('error') raise TypeError finally: print('last line') Output: error last line ZeroDivisionError TypeError Why did the ZeroDivisionError has occurred here even we have print statement instead of ZeroDivisionError? Other e.g: try: print(4/0) except: raise TypeError print('error') finally: print('last line') Output: Last line ZeroDivisionError TypeError Why didn't the print statement got executed here?

9th Apr 2019, 2:36 PM
paperinflames
paperinflames - avatar
5 Antworten
+ 2
If you raise an error (by force or unexpected), program execution stops - unless you catch it with an except. Therefore it needs to be in a try block. If an error gets raised in an except, there is nothing to catch it. Why is the 'old' exception printed out? When in one error situation other errors occur, they get chained together for complete error information. In a complex situation that can help you understand the bug.
9th Apr 2019, 2:52 PM
HonFu
HonFu - avatar
+ 2
Okay, in more detail. try: print(4/0) ZeroDivisionError is raised. except: This except stops the Error - for now. raise TypeError But now you manually raise an Error of your own. Since this error is not in a try block, program stops. print('error') So this line is not executed. You get a complete report of both errors. finally: print('last line') This though is executed, since finally has this job, to execute the code in there no matter what.
9th Apr 2019, 3:07 PM
HonFu
HonFu - avatar
+ 1
Cool. By seeing the output we can understand that finally's statement is executed first. Is that is the work flow? HonFu
9th Apr 2019, 3:15 PM
paperinflames
paperinflames - avatar
+ 1
The finally block is executed the moment an exception can't be caught anymore. Then the program terminates and you get your full report.
9th Apr 2019, 3:41 PM
HonFu
HonFu - avatar
0
https://code.sololearn.com/cE1IlCogyxRk/?ref=app HonFu please run this code you can understand
9th Apr 2019, 3:01 PM
paperinflames
paperinflames - avatar