Is it possible in Python, to catch an exception at the current function level, but not from called sub functions?
Please consider this example:
def func(some_dict):
print(some_dict["special_value"])
some_dict = {
"general_value": True,
# "special_value": True
}
try:
if some_dict["general_value"]:
func(some_dict)
except KeyError:
print("General value not set")
I would like to catch the KeyError that if some_dict["general_value"]:
might throw, but raise any KeyErrors from within func(...)
However, the example above will show General value not set
although the key general_value
is set.
I can think of the following workaround, but I'm wondering if there's a better way
temp_value = None
try:
temp_value = some_dict["general_value"]
except KeyError:
print("General value not set")
if temp_value:
func(some_dict)
Another way to ask this question: Is it possible to exclude certain parts within a try/except
block from being caught?
Your workaround is the right general idea, but can be done more neatly as:
try:
some_dict["general_value"]
except KeyError:
print("General value not set")
else:
func(some_dict)
or perhaps:
if "general_value" in some_dict:
func(some_dict)
else:
print("General value not set")
which seems a little clearer to me.
you could use a nested try/except - but this is not recommended.
try:
if some_dict["general_value"]:
try:
func(some_dict)
except KeyError:
print("special error")
except KeyError:
print("general value not set")
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.