Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can my program know an exception from a separate method [duplicate]

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!

like image 677
Darren.c Avatar asked Sep 19 '25 06:09

Darren.c


1 Answers

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
like image 189
MisterMiyagi Avatar answered Sep 20 '25 20:09

MisterMiyagi