Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple Tries in Try/Except Block

I have some python code where I can accept two different file names, so I would like to do something like try the first file name, if there is an exception then try the second filename, if the second try fails, then raise the exception and handle the error.

So the basic logic is:

first try this:
   f = file(name1)
if not, then try this
   f = file(name2)
else
   error()

I'm pretty sure I could do this with nested try/except blocks, but that doesn't seem like a good solution. Also, if I want to scale up to something like 20 different filenames, then nesting the try/except blocks would get really messy.

Thanks!

like image 218
devin Avatar asked Jan 27 '11 17:01

devin


People also ask

Can try block have multiple except blocks?

It is possible to have multiple except blocks for one try block.

How do I stop multiple try-except?

To avoid writing multiple try catch async await in a function, a better option is to create a function to wrap each try catch. The first result of the promise returns an array where the first element is the data and the second element is an error. And if there's an error, then the data is null and the error is defined.

How many except block can a try have?

1. How many except statements can a try-except block have? Answer: d Explanation: There has to be at least one except statement.

Can I have multiple try catch in a function?

A try statement can include multiple catch blocks for the different specified error types.


2 Answers

You could simply use a for loop:

for name in filenames:
    try:
        f = open(name)
        break
    except IOError:
        pass
else:
    # error
like image 192
Sven Marnach Avatar answered Oct 04 '22 20:10

Sven Marnach


You can do a loop of try ... except like:

for f_name in names:
    try:
        f = open(f_name, 'r')
        # do something
        break # Exit from the loop if you reached this point
    except:
        print 'error, going to try the next one'
like image 44
Elalfer Avatar answered Oct 04 '22 19:10

Elalfer