Nested functions exception handling
Original question asked in Real Python slack group:
I have a question about chained exception handling method and how to return except conditions when I use it for one function which relies on another function. The code can be found below for more context: https://gist.github.com/kurianbenoy/59bc813b535adc3a739f87dd4d4f4fb7 It looks to me from answers I got from experienced folks in Real python, there are two ways to do this:
In main function write try/except code and raise the exception from nested inner function Hello this is my rewriten code which required a custom class in Python: py class ModelNotSupported(Exception): pass https://gist.github.com/kurianbenoy/346090c325dcf4f8f77ec3fbda3f0f99
1
supported = ["a", "b", "c", "en", "ta"]
2
3
4
def load_model(source, target):
5
if source == target:
6
raise ModelNotSupported("Hello how are you")
7
if source in supported:
8
if source == "en":
9
return ("t", "t")
10
else:
11
raise ModelNotSupported("Language pair not available")
12
13
14
def predict_raw():
15
try:
16
tokenizer, model = load_model("en", "hello")
17
return model
18
except ModelNotSupported as e:
19
return {"inputerror": e}
Copied!
This can be be implemented with a function which returns messages, and based on which return based on the conditions.
1
Copied!
Copy link