Import Sys
# ===Catching exceptions(can be flexibly combined) ===
DefEXCEP ():
#-Try except-
Try
Print (ex)
Except#Catch all exceptions
Print"Catching exceptions!")
Try
Print (ex)
Except#Get exception information by function
Types, value, back = Sys.exc_info ()#Catching exceptions
Sys.excepthook (types, value, back)#Printing exceptions
Try
Print (ex)
ExceptNameerror:#Capturing the specified exception
Print"Catch name undefined exception!")
ExceptIOError:
Print"CaptureIoAbnormal!")
Except
Print"Catch all exceptions!")
Try
Print (ex)
Except (Nameerror,IOError)As e:#Capturing multiple exceptions at the same time,And tell the cause of the anomaly
Print"Capturing multiple exceptions!")
Print (e)
Except
Print"Catch all exceptions!")
#-Try except else-
Try
Pass
Except
Print"Catching exceptions!")
Else#No exception occurs when the code block is executed
Print"Operating normally.")
#-Try except else finally-
Try
Pass
Except
Print"Catching exceptions!")
Else
Print"Operating normally.")
Finally#Executes regardless of whether an exception occurred
Print"Executes regardless of whether an exception occurred")
# ===Custom exceptions===
# -Writing custom Exceptions-
Class Myerror (Exception):#InheritedException
#Rewrite andSuperStructure
Def__INIT__ (Self, mes ="Throws an exception."):
Exception.__INIT__ (Self
Self.message = mes
Def__STR__ (Self):
return Self.message
#- Use custom exceptions -
def Myerr ():
Try:
Raise Myerror (" throw exception !") # throws an exception
except Myerror as e: # catching exceptions
Print (e)
# ===Assertion statement===
DefAssertdemo ():
#Assertions are typically used for testing,If the test result isFlase,Will throwAssertionerrorAbnormal
AssertType"String")is str
assert 3 < 4
assert 4< Span style= "COLOR: #cc7832", " throw assertionerror exception " Span style= "COLOR: #6a8759" >
# ======= function call ======
if __name__ = "__main__":
Excep ()
Myerr ()
Assertdemo ()
python3-Note-d-001-exceptions and assertions