>>>whileTrue:try:x=int(input("Please enter a number: "))break;exceptValueError:print("Oops! That was not a valid number. Try again...")
try statement will work as follows:
statements between try and except are executed.
If no exception occurs, try statement is finished.
If one exception occurs, the rest of the statements will be skipped.
If the exception type matches the name after except keyword.The except statement will be executed, then execution continues after the try
** If the exception type does not match all except names. It is an unhandled exception and execution will stop.
Multiple excepts may share the same except statement.
The last except clause can be used as a wildcard to alert the programmer and re-raise the exception.
12345678910111213
importsystry:f=open('myfile.txt')s=f.read()i=int(s.strip())exceptOSErroraserr:print("OS error: {0}".format(err))exceptValueError:print("Cloud not convert data to an integer.")except:print("Unexpected error:",sys.exec_info()[0])raise`
try ... except can has an optional else clause. The else clause will be used if try does not raise an exception.
You can specify a variable after the exception name. The variable is stored in instance.args
123456789101112131415
try:raiseException('spam','eggs')exceptExceptionasinst:print(type(inst))# print the type of exception instanceprint(inst.args)# print the argumentsprint(inst)# print the argumentsx,y=inst.args# unpack the argsprint(x)print(y)<class'Exception'>('spam','eggs')('spam','eggs')x=spamy=eggs
Raising Exceptions
raise statement allows the programmer foce a specified except to occur. The except must be an exception instance or an exception class
If you do not want to handle the exceptions, you can use raise to re-raise the exception
12345678910
>>>try:raiseNameError('HiThere')exceptNameError:print('An exception flew by!')raise# re-raise the NameErrorAnexceptionflewby!Traceback(mostrecentcalllast):File"<stdin>",line2,in?NameError:HiThere
User-defined Exceptions
The new exceptions should be derived from Exception class
123456789101112131415161718
>>>classMyError(Exception):def__int__(self,value):# override the default __init__()self.value=valuedef__str__(self):returnrepr(self.value)>>>try:raiseMyError(2*2)exceptMyErrorase:print('My exception occurred, value:',e.value)Myexceptionoccurred,value:4>>>raiseMyError('oopos!')Traceback(mostrecentcalllast):File"<stdin>",line1,in?__main__.MyError:'oops!'
It is a common practice to create a base class for exceptions then define subclass to create specific exception.
123456789101112
classError(Exception):# base classclassInputError(Error):# inputErrordef__int__(self,expression,message):self.expression=expressionself.message=messageclassTransitionError(Error)def__int__(self,previous,next,message):self.previous=previousself.next=nextself.message=message
Predefined Clean-up Actions
with statement allows objects to be cleaned up after it is not used.