Python3

Try except else finally

2022-01-13  本文已影响0人  JaedenKil
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")
Else
Finally
ExceptionA
Finally
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

上一篇下一篇

猜你喜欢

热点阅读