您的位置:首页 > 编程语言 > Python开发

python异常处理救命代码

2014-05-12 00:00 302 查看
#!/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)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python exception class go