try:
file = open("test1.txt","r")
print(file.read())
file.close()
# except Exception:
except (IOError,ZeroDivisionError):
print("出错了")
print("哈哈哈哈哈")
try:
file = open("test1.txt","r")
print(file.read())
file.close()
except IOError as result:
print(result)
try:
file = open("test1.txt", "r")
try:
print(file.read())
except IOError as result:
print(result)
else:
print("没有异常")
finally:
file.close()
except:
print("文件出错了")
try:
file = open("test1.txt", "r")
try:
while True:
content = file.readline()
if len(content) == 0:
break
except IOError as result:
print(result)
else:
print("没有异常")
finally:
file.close()
except:
print("文件出错了")
自定义异常
class ShortInputException(Exception):
def __init__(self,length,atleast):
self.length = length
self.atleast = atleast
def __str__(self):
return "ShortInputException: 输入的长度是 %d,长度至少应是 %d" %(e.length,e.atleast)
try:
s = input("please input:")
if len(s) < 3:
raise ShortInputException(len(s),3)
except ShortInputException as e:
print(e)