All of Python's exceptions inherit from the base class: Exception
Handled in a similar way to Java:
Path = Raw_input ('Input the path') Array= Path.split ('/')Try: module= __import__ ('model.'+ array[0]) Model= GetAttr (module, array[0]) func= GetAttr (model, array[1] func () except (Importerror, Attributeerror, Nameerror), E:print (e)finally: Print ('finally to do')
Multiple exception snaps, either using a continuous exept or using parentheses for snapping
Import SYSTry: F= Open ('MyFile.txt') s=f.readline () I=int(S.strip ()) except OSError asErr:print ("OS Error: {0}". Format (ERR)) except Valueerror:print ("Could not convert data to an integer.") Except:print ("Unexpected error:", Sys.exc_info () [0]) Raise
else:
Print (' Else method ')
Python's exception has an ELSE clause that executes without any exception.
Custom Exceptions:
Like other languages, Python can also make custom exceptions and throw them;
class myexception (Exception): def __init__ (self, name): = name # Override string method *args, * * Kwargs): return self.name
The way to throw in other places:
Try : print ('start ... ' ) raise MyException ('raise exception' as err: print (ERR) finally : print ('finally')
Use the Raise keyword to throw
Exceptions in the 05-python