python异常处理示例代码
来源:互联网 发布:php页面跳转url不变 编辑:程序博客网 时间:2024/05/29 19:19
#!/usr/bin/env python# -*- coding: utf-8 -*-import systry: 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] raiseelse: 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 - finallydef 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)