现在的位置: 首页 > 综合 > 正文

python异常处理救命代码

2014年02月20日 ⁄ 综合 ⁄ 共 732字 ⁄ 字号 评论关闭
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import sys

try:
    f = open('myfile.txt')
    s = f.readline()
    i = int(s.strip())
except IOError as (errno, strerror):
    print "I/O error({0}): {1}".format(errno, strerror)
except ValueError:
    print "Could not convert data to an integer."
except:
    print "Unexpected error:", sys.exc_info()[0]
    raise
else:
    print "I will always go here if there is no except!"

#自定义异常处理
class MyError(Exception):
    def __init__(self, value):
        self.value = value
        
    def __str__(self):
        return repr(self.value)
        
try:
    raise MyError(2*2)
except MyError as e:
    print "My exception occured, value: ", e.value
    
#raise MyError('oops!')

# try - except - else - finally
def divide(x, y):
    try:
        result = x / y
    except ZeroDivisionError:
        print "Divide by zero"
    else:
        print "The result is ", result
    finally:
        print "executing finally clause"
        
divide(2, 1)

divide(2, 0)

抱歉!评论已关闭.