Python: 如何写一个异常

例子1

try:
       #test area     
        function()
except Exception, e:
        print e.message    

例子2:用raise抛出一个异常

if bool_var is not True:
        raise Exception

#other statements
#......

expect Exception:
        do_something()

例子3:输出异常到log

import traceback
import logging
  
except Exception as e:
        print(e)
        logging.error("Error: 
%s" % traceback.format_exc())
        #OR logging.error(e)

#log format:
#ERROR: xxx

   

一、try/expect

try:
    #...
expect: ##
    #...
finally:
    #...

可以没有finally语句;finally如果有,则一定会被执行。  

捕捉一个异常:

expect IOError:
        print(...)

多个expect语句,会按顺序检测错误类型:

try:
    print('try...')
    r = 10 / int('a')
    print('result:', r)
except ValueError as e:
    print('ValueError:', e)
except ZeroDivisionError as e:
    print('ZeroDivisionError:', e)
finally:
    print('finally...')
print('END')

用一个块捕捉多个异常:

except (ZeroDivisionError, NameError, TypeError):
        print('Errors!')

全捕捉: 

try:
        ##
expect:
        print('Error!')

 

try/expect  - else:子句 

如果没有错误发生,可以在except语句块后面加一个else,当没有错误发生时,会自动执行else语句:

try:
    print('try...')
    r = 10 / int('2')
    print('result:', r)
except ValueError as e:
    print('ValueError:', e)
except ZeroDivisionError as e:
    print('ZeroDivisionError:', e)
else:
    print('no error!')
finally:
    print('finally...')
print('END')

  

  

  

原文地址:https://www.cnblogs.com/eniac1946/p/8583013.html