user13982022
user13982022

Reputation: 57

Try every line without exception prematurely breaking code

I would like to write a single try-except statement that is able to run multiple try statements without the code breaking.

s = "hello, this is a string."

Using the above string as an example:

ls = []
try:
    ls.append(s.split())
    ls.append(s.str.split()) # expected error
    ls.append(s.split(","))
    ls.append(s.split("i"))
except:
    pass

Above is what I tried originally but the code stops by the second try-statement.

ls = []
try:
    ls.append(s.split())
except:
    pass
try:
    ls.append(s.str.split()) # expected error
except:
    pass
try:
    ls.append(s.split(","))
except:
    pass
try:
    ls.append(s.split("i"))
except:
    pass

Eventually, I was able to get all my strings appended to the list with the above code. Is there a better way of doing this than writing individual try-except statements?

Upvotes: 0

Views: 168

Answers (2)

Vincent
Vincent

Reputation: 11

From my understanding, when an error occurs in a try statement, it will immediately go to the except statement which is why your code doesn't execute after the second try statement.

Though there are probably better solutions to your question, here is my attempt for your problem:

ls = []
char=[' ',',','i']

for i in char:    
    try:
        ls.append(s.split(i))
        ls.append(s.str.split(i))
    except:
        pass
print(ls)



      

Upvotes: 1

bahdotsh
bahdotsh

Reputation: 459

You can use the fuckit module.
Wrap your code in a function with @fuckit decorator:

import fuckit

@fuckit
def func():
    code a
    code b #if b fails, it should ignore, and go to c.
    code c #if c fails, go to d
    code d

Or you can try this :

def a():
    try: # a code
    except: pass # or raise
    else: return True

def b():
    try: # b code
    except: pass # or raise
    else: return True

def c():
    try: # c code
    except: pass # or raise
    else: return True

def d():
    try: # d code
    except: pass # or raise
    else: return True

def main():   
    try:
        a() and b() or c() or d()
    except:
        pass

Upvotes: 1

Related Questions