Using multiple exceptions in Python?
Question:
I’m trying to figure out how to write multiple exceptions for an IPAM API, which means that when one prefix is full, it should take the next one.
this works with one, but not with several different:
dict_endpoints = {"vpn-1": 9,
"vpn-2": 67,
"vpn-3": 68,
"vpn-4": 69}
def api(var_endpoint):
url = "https://myURL.org/"
token = os.environ['NETBOXTOKEN']
nb = pynetbox.api(url=url, token=token)
prefix = nb.ipam.prefixes.get(var_endpoint)
new_prefix = prefix.available_prefixes.create({"prefix_length": 48})
print(new_prefix)
try:
api(dict_endpoints["vpn-1"])
except:
api(dict_endpoints["vpn-2"])
# multiple exceptions without exiting the script
#except:
# api(dict_endpoints["vpn-3"])
Answers:
You could create a loop:
for endpoint in dict_endpoints.values():
try:
api(endpoint)
break # success!!
except:
pass # ignore error and go to next iteration
else: # all failed :-(
print("all endpoints failed...")
You can use else statement or handle multiple excepts like this:
try:
--snip--
except (exception_1, exception_2):
--snip--
else:
--snip--
I’m trying to figure out how to write multiple exceptions for an IPAM API, which means that when one prefix is full, it should take the next one.
this works with one, but not with several different:
dict_endpoints = {"vpn-1": 9,
"vpn-2": 67,
"vpn-3": 68,
"vpn-4": 69}
def api(var_endpoint):
url = "https://myURL.org/"
token = os.environ['NETBOXTOKEN']
nb = pynetbox.api(url=url, token=token)
prefix = nb.ipam.prefixes.get(var_endpoint)
new_prefix = prefix.available_prefixes.create({"prefix_length": 48})
print(new_prefix)
try:
api(dict_endpoints["vpn-1"])
except:
api(dict_endpoints["vpn-2"])
# multiple exceptions without exiting the script
#except:
# api(dict_endpoints["vpn-3"])
You could create a loop:
for endpoint in dict_endpoints.values():
try:
api(endpoint)
break # success!!
except:
pass # ignore error and go to next iteration
else: # all failed :-(
print("all endpoints failed...")
You can use else statement or handle multiple excepts like this:
try:
--snip--
except (exception_1, exception_2):
--snip--
else:
--snip--