美文网首页Python3
Try except else finally

Try except else finally

作者: JaedenKil | 来源:发表于2022-01-13 11:26 被阅读0次
class ExceptionA(Exception):
    pass


class ExceptionB(Exception):
    pass


def foo(i: int):
    if i > 0:
        raise ExceptionA
    elif i < 0:
        raise ExceptionB
    else:
        pass


if __name__ == "__main__":
    try:
        foo(0)
    except ExceptionA as ex:
        print("ExceptionA")
    else:
        print("Else")
    finally:
        print("Finally")
  • Run foo(0):
Else
Finally
  • Run foo(1):
ExceptionA
Finally
  • Run foo(-1):
Finally

Try: This block will test the excepted error to occur
Except: Here we can handle the error
Else: If there is no exception then this block will be executed
Finally: Finally block always gets executed either exception is generated or not

相关文章

网友评论

    本文标题:Try except else finally

    本文链接:https://www.haomeiwen.com/subject/drjncrtx.html