from Tools.scripts.treesync import raw_input
import sys, os, time
#处理异常, try ... except
while True:
try:
x = int(raw_input("输入一个Number:"))
break
except ValueError:
print("Oops! that was no valid number: Try again.")
#exception 兼容的类
class B(Exception):
pass
class C(B):
pass
class D(C):
pass
for cls in [B, C, D]:
try:
raise cls()
except D:
print("D")
except C:
print("C")
except B:
print("B")
#异常的else从句
try:
f = open("myfile.txt")
s = f.readline()
i = int(s.strip())
except OSError as err:
print(("OS error: {0}".format(err)))
except ValueError:
print("不能转为整数")
except:
print("伟处理异常", sys.exec_info()[0])
raise
try:
f = open("myfile.txt")
s = f.readline()
i = int(s.strip())
except OSError as err:
print("文件不能打开")
else:
print("else从句")
f.close()
#读取异常内容,异常参数
try:
raise Exception("spam", 'eggs')
except Exception as err:
print(type(err))
print(err.args)
print(err)
x,y = err.args
print("x =", x)
print("y =", y)
#捕获函数异常
def this_fails():
x = 1 / 0
try:
this_fails()
except ZeroDivisionError as err:
print("运行时错误:", err)
# 抛出异常
try:
raise NameError("你好")
except NameError as err:
print("捕获的异常,", err.args)
#自定义异常
class Error(Exception):
pass
class InputError(Error):
def __init__(self, expression, message):
self.expression = expression
self.message = message
class TransitionError(Error):
def __init__(self, previous, next, message):
self.previous = previous
self.next = next
self.message = message
try:
raise InputError(" 3 / 0 = ?", "自定义输入错误")
except InputError as err:
print("自定义错误 =",err.args)
#资源释放
def divide(x, y):
try:
result = x / y
except ZeroDivisionError:
print("被0除的错误")
else:
print("计算结果 =", result)
finally:
print("这里可以放释放资源的代码")
divide(3, 0)
#使用with自动释放资源
file_name = os.path.abspath("abc\\myfile.txt")
with open(file_name) as f:
for line in f:
print(line, end = "")