自定义异常

异常通常直接或间接的从Exception类派生

  
    
# ! /usr/bin/python

import sys,os

class MyError(Exception):
def __init__ (self,value):
self.value
= value
def __str__ (self):
return repr(self.value)

try :
f
= open( ' myfile.txt ' )

except IOError, (errno,strerror):
print " I/O error(%s): %s " % (errno,strerror)

# raise NameError, "Just for test! "
raise MyError, " my error is raised! "

 

the result:

  
    
Traceback (most recent call last):
File
" test.py " , line 18 , in <module >
raise MyError,
" my error is raised! "
__main__.MyError: 'my error is raised
! '

 

你可能感兴趣的:(自定义异常)