repeat Try and except with different option

37 views Asked by At

in this case this is working fine for me but it just add like 4 seconds extra for the code to run

try:
    val1 = a
except:
    try:
        val1 = b    
    except:
        try:
            val1 = c
        except:
            try:
                val1 = d
            except:
                try:
                    val1 = e
                except:
                    pass

Is there a better way to make many try and except?

1

There are 1 answers

0
V Z On
  1. Use a try-except with multiple except clauses:
try:
    val1 = a
except (NameError, ValueError):  # Handle multiple exceptions
    val1 = b
except (KeyError, IndexError):  # Handle other exceptions
    val1 = c
except:  # Catch-all for any other exception
    val1 = None  # Or handle it differently
  1. Use a loop with conditional assignment
for value in [a, b, c, d, e]:
    try:
        val1 = value
        break  # Exit the loop if successful
    except:
        pass  # Continue to the next value

if val1 is None:
    # Handle case where no value was assigned
  1. Use a dictionary lookup
value_map = {
    'a': lambda: a,
    'b': lambda: b,
    'c': lambda: c,
    'd': lambda: d,
    'e': lambda: e,
}

try:
    val1 = value_map[variable_containing_key]()
except KeyError:
    # Handle invalid key
except Exception as e:
    # Handle other exceptions