#!/usr/bin/env python
class Functions() :
def A(self):
print "hey"
self.B()
return 1
def B(self):
print "hello"
exit(0)
func_obj = Functions()
def main() :
A = func_obj.A()
print A
print "awesome"
if __name__ == '__main__' :
main()
以上是我的代码。我想做的是要从functionA
函数调用main()
,并且当functionA
执行functionB
时,我希望functionB
引发错误并返回到main()
函数而不返回到functionA
。我该如何实现?基本上,我希望main函数在"awesome"
退出后打印functionB
。我不确定要查找的正确关键字是什么。
答案 0 :(得分:0)
您要寻找的是exceptions-实际上,它们的用途是:break the normal flow of execution and propagate up the call stack,直到有人照顾好它们为止(作为最后的选择,运行时将捕获它们并显示它们。错误消息和完整的回溯,然后退出)。
该过程分为两个部分:首先引发异常,然后在正确的位置捕获异常。在您的示例中,它可能看起来像:
# declare our own exception type so we can catch specifically this one
class MyOwnException(Exception):
pass
def a():
print("in a - before b")
b()
print("in a - after b (shouldn't see this)")
def b():
print("in b, before raise")
raise MyOwnException("hello houston ?")
print("in b, after raise (shouldn't see this)")
if __name__ == "__main__":
print("calling a")
try:
a()
print("after a (shouldn't see this)")
except MyOwnException as e:
print("caugth error {}".format(e))
FWIW,您使用exit()
的示例非常接近,因为exit()
实际上是通过引发SysExit
异常来工作的。异常的第一个也是主要的用例当然是错误处理,但这实际上是控制程序的执行流的一种方式(例如,StopIteration
异常用于表示疲惫的迭代器)。
答案 1 :(得分:-2)
嘿,所以当有人指出我的原始答案无效后,我便开始搜索!您可以创建自定义异常类以实现所需的功能!
class HaltException(Exception):
pass
class Functions():
def a(self):
print("hey")
self.b()
return "1"
def b(self):
print("hello")
raise HaltException("This is an exception error.")
def main():
func_obj = Functions()
try:
func_obj.a()
except HaltException as error:
print(error)
print("Awesome")
if __name__ == "__main__":
main()
这将在运行时返回以下内容:
hey
hello
This is an exception error.
Awesome