Python 从主功能的子功能退出

Python 从主功能的子功能退出,python,python-2.7,Python,Python 2.7,上面是我的代码。我想做的是,我想从主函数调用function,当function执行functionB时,我想functionB引发错误并退出到主函数,而不返回function。我怎样才能做到这一点?基本上,我希望主函数在函数B退出后打印awesome。我不确定什么是正确的关键字来查找它 嘿,有人指出我原来的答案不起作用后,我就去搜索了!您可以创建自定义异常类来实现所需的功能 #!/usr/bin/env python class Functions() : def A(self):

上面是我的代码。我想做的是,我想从主函数调用function,当function执行functionB时,我想functionB引发错误并退出到主函数,而不返回function。我怎样才能做到这一点?基本上,我希望主函数在函数B退出后打印awesome。我不确定什么是正确的关键字来查找它

嘿,有人指出我原来的答案不起作用后,我就去搜索了!您可以创建自定义异常类来实现所需的功能

#!/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()
然后,运行时将返回以下内容:

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

FWIW,您使用exit的示例非常接近,因为exit实际上是通过引发SysExit异常来工作的。异常的第一个也是主要的用例当然是错误处理,但它实际上是控制程序执行流的一种方法。例如,StopIteration异常用于向耗尽的迭代器发出信号。

Return返回函数a:/正是我所寻找的!非常感谢你们!无声地传递异常几乎总是一个坏主意,当然除了那些-比如StopIteration-明确用作执行流控制。嗨,伙计们,抱歉,只是确认一下,上面的代码中做了更改,更改只是发送错误消息。这是一个异常错误。在提升暂停期间,感觉是否正确?布鲁诺指出,在不发送错误消息的情况下引发异常不是一个好主意?正确。悄悄地传递异常可能会导致很多问题,所以请稍微详细一点嘿,检查我更新的答案
# 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))