25-Python3 错误和异常

'''
语法错误
'''
# while True print('hello,runoob') '''
异常
'''
##ZeroDivisionError
# print(10*(1/0)) ##NameError
# print(4+spam*3) ##TypeError
# print('2'+2) '''
异常处理
'''
# while True:
# try:
# x = int(input('please enter a number:'))
# break
# except ValueError:
# print('Oops!that was no valid number!try again') # import sys,os
# fo_error = open('/Users/ligaijiang/PycharmProjects/foo_error.txt','w')
# fo_error.close()
#
# str_error = 'hello,runoob'
# n = 0
# d = 1
# for i in range(5):
# print('第{0}行:{1}'.format(n,str_error))
# n = n +1
# d = d +1
# try:
# f = open('/Users/ligaijiang/PycharmProjects/foo_error.txt')
# s = f.readline()
# i = int(s.strip())
# except OSError as err:
# print('OS error:{}'.format(err))
# except ValueError:
# print('Could not convert data to an integer')
# except:
# print('Unexpected error:',sys.exc_info()[0])
# raise # import sys,os
#
# for arg in sys.argv[1:]:
# try:
# f = open(arg,'r')
# except IOError:
# print('cannot open',arg)
# else:
# print(arg,'has',len(f.readline()),'lines')
# f.close() # def this_fails():
# x = 1/0
# try:
# this_fails()
# except ZeroDivisionError as err:
# print('Handling run-time error',err) '''
抛出异常
'''
##使用raise语句抛出一个指定的异常
# raise NameError('HiThere') ##
# try:
# raise NameError('HiThere')
# except NameError:
# print('An exception flew by')
# raise '''
用户自定义异常
'''
# class MyError(Exception):
# def __int__(self,value):
# self.value = value
# def __str__(self):
# return repr(self.value)
# try:
# raise MyError(2*2)
# except MyError as e:
# print('My exception occurred,value:',e.value) '''
定义清理行为
'''
#定义另无论在任何情况下都会执行的清理行为
# try:
# raise KeyboardInterrupt
# finally:
# print('Goodbye,world') #
# def divide(x,y):
# try:
# result = x / y
# except ZeroDivisionError:
# print('division by zero!')
# else:
# print('result is',result)
# finally:
# print('executing finally clause')
#
# divide(2,1)
# divide(2,0)
# divide('2','1') '''
预定义的清理行为
''' fo_5 = open('/Users/ligaijiang/PycharmProjects/foo_5.txt','w')
fo_5.close() s_5 = 'hello,runoob.'
n = 0
d = 1
for n in range(5):
print('第{0}行:{1}'.format(d,s_5))
n = n+1
d = d+1 #没有关闭文件
# for line in open('/Users/ligaijiang/PycharmProjects/foo_5.txt'):
# print(line,end='') #会关闭文件
with open('/Users/ligaijiang/PycharmProjects/foo_5.txt') as f_5:
for line in f_5:
print(line,end='')
05-08 08:42