I have a Python script that needs to look for a certain file.
I could use os.path.isafile(), but I've heard that's bad Python, so I'm trying to catch the exception instead.
However, there's two locations I could possibly look for the file. I could use nested trys to handle this:
try:
keyfile = 'location1'
try_to_connect(keyfile)
except IOError:
try:
keyfile = 'location2'
try_to_connect(keyfile)
except:
logger.error('Keyfile not found at either location1 or location2')
Or I could just put a pass in the first except block, and then have another one just below:
try:
keyfile = 'location1'
try_to_connect(keyfile)
except IOError:
pass
try:
keyfile = 'location2'
try_to_connect(keyfile)
except:
logger.error('Keyfile not found at either location1 or location2')
However, is there a more Pythonic way to handle the above situation?
Cheers, Victor
By handling multiple exceptions, a program can respond to different exceptions without terminating it. In Python, try-except blocks can be used to catch and respond to one or multiple exceptions. In cases where a process raises more than one possible exception, they can all be handled using a single except clause.
Nested try block is a block in which we can implement one try catch block into another try catch block. The requirement of nested try-catch block arises when an exception occurs in the inner try-catch block is not handled by the inner catch blocks then the outer try-catch blocks are checked for that exception.
Python provides the ability to open as well as work with multiple files at the same time. Different files can be opened in different modes, to simulate simultaneous writing or reading from these files.
Can one block of except statements handle multiple exception? Answer: a Explanation: Each type of exception can be specified directly. There is no need to put it in a list.
for location in locations:
try:
try_to_connect(location)
break
except IOError:
continue
else:
# this else is optional
# executes some code if none of the locations is valid
# for example raise an Error as suggested @eumiro
Also you can add an else
clause to the for loop; that is some code is executed only if the loop terminates through exhaustion (none of the locations is valid).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With