so my question is that in my code actually on consists of two python module on the main and other the sub. In sub there is a function which I need to stop the working and return the control back to the next line of the main module. How can it be done. I tried exit() but it stops the execution. just for example
#module 1 -- ex2
import ex1
def add():
print('before calling ex1')
ex1.sub()
print('after calling ex1')
add()
#module 2 -- ex1
def sub():
print('inside sub')
error()
print('after error call')
def error():
print('inside error')
return #in place of this
so I want is that when my code enters the error function it will print the statement and the module 2 ends execution and the control will flow to the print('after calling ex1') this statement in module 1. Please help guys
note: please do not use multiple returns as example:
#module 2 -- ex1
def sub():
print('inside sub')
error()
return # Please do not use
print('after error call')
def error():
print('inside error')
return #in place of this
I need the output to be like ---
before calling ex1
inside sub
inside error
after calling ex1
2 Answers 2
This is what exception handling is designed for, with the raise statement and the try .. except construct in Python:
#module 1 -- ex2
import ex1
def add():
print('before calling ex1')
try:
ex1.sub()
except RuntimeError as e:
print('An error occurred while calling ex1.sub:', str(e))
# or just a pass statement if you do not want anything done about the error
print('after calling ex1')
add()
#module 2 -- ex1
def sub():
print('inside sub')
error()
print('after error call')
def error():
print('inside error')
raise RuntimeError('some error')
2 Comments
passYour error function must be a function that returns a value. True or False
def error():
print('inside error')
return True
# or return False
def sub():
print('inside sub')
if(error()):
return
print('after error call')
try/except