First, catch the exception
1, when the program error, will not show the bug information to the user, but to provide a friendly prompt, continue to execute the program
2, the following, to achieve division, when the denominator is 0 o'clock, capture and print out the exception information; exception can catch any exception
def Div (x, y): Try : Print (x/y) except Exception as E: Print (' exception is ', E)
>>> Div (1,0)
Exception is division by zero
You can also specify that the exception is Zerodivisionerror
def Div (x, y): Try : Print (x/y) except Zerodivisionerror as E: Print (' exception is ', E)
>>> Div (1,0)
Exception is division by zero
3. Capturing multiple exceptions at the same time
deffdiv (x, y):Try: returnx/yexceptTypeError as E:Print('TypeError:', E)exceptZerodivisionerror as E:Print('Zerodivisionerror:', E)exceptException as E:Print('Other Exceptions:'E
>>> fdiv (' ABC ', 0)
typeerror:unsupported operand type (s) for/: ' str ' and ' int '
>>> Fdiv (12,0)
Zerodivisionerror:division by Zero
You can also use the following methods:
def fdiv1 (x, y ): Try : return x/y except (TypeError, Zerodivisionerror, Exception) as E: Print (e)
>>> fdiv1 (' ABC ', 0)
Unsupported operand type (s) for/: ' str ' and ' int '
>>> Fdiv1 (12,0)
Division by zero
Second, common anomalies
'---------------IOError: Open File path error or not present------------------'Try: F= Open ('Error.txt','R')exceptIOError as E:Print('Error opening file:', E)'--------------importerror: The Import module path is faulty or does not exist--------------'Try: ImportErrorexceptImporterror as E:Print('Import module error, error message:', E)'--------------indexerror: Index out of bounds----------------------------'List1= [1,2,3,4,5,6]Try: Print(list1[6])exceptIndexerror as E:Print('Query list error, error message:', E)'----------------keyerror: Find a keyword that does not exist in the dictionary---------------'Dict1= {1:'A', 2:'B'}Try: Print(dict1[3])exceptKeyerror as E:Print('Query dictionary error, error message:', E)'----------------TypeError: Parameter types do not match----------------------'defFint (a):Print(A/2)Try: str1='ABC'Fint (str1)exceptTypeError as E:Print('parameter type error, error message:', E)'------------valueerror: The parameter type matches, but the value passed in is not------------'str1='ABC'Try: Print(int (str1))exceptValueError as E:Print('parameter value error, error message:', E)'------------------nameerror: The variable used is not assigned a value------------------'Try: Print(a)exceptNameerror as E:Print('parameter error, error message:'E
Third, custom exceptions
class myexception (Exception): def __init__ (Self, msg): = msg def__str__(self): return self.message try: raise myexception (' Custom exception ' ) )except myexception as E: print(e)
Four, the initiative throws the exception
Try : Raise IOError (' Error reading/writing file ') # actively throws IOError exception except IOError as E: print(e)
Wu, try-except-else-finally
Try: F= Open ('Test.txt','R')exceptIOError as E:#打开文件失败, youThrow Exception Print(e)Else:#The open file succeeds, then the else block is executed Print('Execute Else') F.close ()finally:#the finally block executes regardless of whether the file is open properly Print('Execute finally')
python-Exception Handling