0

In this example I call fun3() in fun2(), but if something special happen in fun3() is there a way to directly return to fun1()? without having to check this special thing in fun2().

def fun1(num):

  res = fun2(num)

  # do something if fun3() return an error...

def fun2(num):

  res = fun3(num) # if fun3(num) return a status:error return to fun(1)

  # something else...

def fun3(num):

  if type(num) is not int:

    return {'status': 'error'}

  else: 

    # something else...

1 Answer 1

4

This is what exceptions are for

def fun1(num):
  try:
    res = fun2(num)
  except Exception:
    # specific exception handling
  # will continue executing

  # something else...

def fun2(num):

  res = fun3(num) # if fun3(num) return a status:error return to fun(1)

  # something else...

def fun3(num):

  if type(num) is not int:

    raise Exception('Status Error')

  else: 

    # continue

You should consider using a specific Exception type, rather than just Exception. Fitting for this problem would be a TypeError.

Sign up to request clarification or add additional context in comments.

6 Comments

Thanks! I didn't know it is possible to catch an exception raised in another function.
You're not in another function, you're still in fun1(). fun3() executes in fun2() which executes in fun1(). If I put a note in an envelope, and then put the envelope in a box, the note is still in the box. Note = fun3, envelope = fun2, and box = fun1.
I know exceptions are used to handle errors but something I need to handle warning or just info (for example Update is not needed), so can I create specific execption types called fetchWarning() and fetchInfo() ? just to return data in the try except in fun1().
I will try to use the Warning module instead.
The error generated with data type was for the example but I have more specific needs so I declared a class for custom warning type with fetchWarning(UserWarning) so now I can raise it and handle it into fun1() with except exceptions.fetchWarning() as w :
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.