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!
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With