+ 1

try: with open(filename, mode) as fileobj: # do something with the open file object except IOError as exc: # handle the exception Is any 1 can explain this code what is the use of try except when we use with for closing file?

31st May 2017, 11:05 AM
Nithya Mk
Nithya Mk - avatar
2 Réponses
+ 1
Try means for python to run the code block under it. If it encounters any exception (error) or a specific one stated with except, it will run the code block underneath that instead. Normally when angry red text occurs, the program is aborted by python. These allow you to tell python what it should do in the event of such errors. Example below tries to first print 2 divided by 0. This of course causes a ZeroDivisionError. But in the case of an error, I told python to instead print another statement: try: print ( 2 / 0 ) except: print ("You cannot divide by zero!")
31st May 2017, 1:48 PM
Sapphire
+ 1
try and catch are used in exception it is like you saying try my code and if any error exists then catch the error here in ur code the use of except is to catch any error related to the filename given in open function.. errors like file not exist. Keep moving forward 💪💪😇.
13th Jun 2017, 7:37 AM
SEMOOOOOOZ
SEMOOOOOOZ - avatar