4

I am writing a python program. It calls a private method which has try...except... and returns a value. Such as:

def addOne(x):
    try:
        a = int(x) + 1
        return a
    except Exception as e:
        print(e)
def main():
    x = input("Please enter a number: ")
    try:
        y = addOne(x)
    except:
        print("Error when add one!")

main()

The output is this when I entered an invalid input "f"

Please enter a number: f
invalid literal for int() with base 10: 'f'

I want to detect the exception in both main() and addOne(x) So the ideal output may looks like:

Please enter a number: f
invalid literal for int() with base 10: 'f'
Error when add one!

Could anyone tell me how to do? Thanks!

Austin
  • 25,759
  • 4
  • 25
  • 48
Darren.c
  • 43
  • 2

1 Answers1

2

Handling an exception prevents it from propagating further. To allow handling the exception also in an outer scope, use a bare raise inside the exception handler:

def addOne(x):
    try:
        a = int(x) + 1
        return a
    except Exception as e:
        print(e)
        raise  # re-raise the current exception
MisterMiyagi
  • 44,374
  • 10
  • 104
  • 119