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")
- 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