异常,是可以改变程序中流程的事件。可以根据错误自动地被触发,也可能由代码触发或截获。
try语句分句形式 | 说明 |
---|---|
except: | 捕捉所有异常类型 |
except name: | 只捕捉特定异常 |
except name as value: | 捕捉所列的异常和其额外的数据 |
except (name1, name2): | 捕捉列出的任何异常 |
except (name1, name2) as value: | 捕捉列出的任何异常,并取得其额外数据 |
else: | 如果没有引发异常,就运行 |
finally: | 总是会运行的代码块 |
def print_addition(a, b):
try:
print("try:")
print(a + b)
print("try end!")
except TypeError as value:
print("except TypeError:")
print("TypeError occurs")
print(value)
else:
print("else:")
print(a, b)
print("no error!")
finally:
print("finally:")
print("finally go!")
def main():
print_addition(1, 2)
print_addition([11, 22, 33], "abc")
if __name__ == "__main__":
main()
'''
输出:
try:
3
try end!
else:
1 2
no error!
finally:
finally go!
try:
except TypeError:
TypeError occurs
can only concatenate list (not "str") to list
finally:
finally go!
'''
def print_addition(a, b):
try:
print("try:")
print(a + b)
print("try end!")
except:
print("raise error!")
raise
else:
print("else:")
print(a, b)
print("no error!")
finally:
print("finally:")
print("finally go!")
def main():
print_addition(1, 2)
print_addition([11, 22, 33], "abc")
if __name__ == "__main__":
main()
'''
输出:
try:
3
try end!
else:
1 2
no error!
finally:
finally go!
try:
raise error!
finally:
finally go!
Traceback (most recent call last):
File "D:/Pycharm/MyProjects/pythonException/Raise.py", line 22, in
main()
File "D:/Pycharm/MyProjects/pythonException/Raise.py", line 19, in main
print_addition([11, 22, 33], "abc")
File "D:/Pycharm/MyProjects/pythonException/Raise.py", line 4, in print_addition
print(a + b)
TypeError: can only concatenate list (not "str") to list
'''
raise exception from otherexception
def raise_from():
try:
1 / 0
except Exception as E:
raise TypeError from E
def main():
raise_from()
if __name__ == "__main__":
main()
'''
输出:
Traceback (most recent call last):
File "D:/Pycharm/MyProjects/pythonException/Raise_2.py", line 3, in raise_from
1 / 0
ZeroDivisionError: division by zero
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "D:/Pycharm/MyProjects/pythonException/Raise_2.py", line 12, in
main()
File "D:/Pycharm/MyProjects/pythonException/Raise_2.py", line 9, in main
raise_from()
File "D:/Pycharm/MyProjects/pythonException/Raise_2.py", line 5, in raise_from
raise TypeError from E
TypeError
'''
assert <test>, <data>
如果test为假,就引发AssertionError,data是额外数据,一般用于传递异常发生的描述。
def assert_test():
assert 1 == 0, "AssertionError occurs!"
def main():
assert_test()
if __name__ == "__main__":
main()
'''
输出:
Traceback (most recent call last):
File "D:/Pycharm/MyProjects/pythonException/Assert.py", line 9, in
main()
File "D:/Pycharm/MyProjects/pythonException/Assert.py", line 6, in main
assert_test()
File "D:/Pycharm/MyProjects/pythonException/Assert.py", line 2, in assert_test
assert 1 == 0, "AssertionError occurs!"
AssertionError: AssertionError occurs!
'''
with expression [as variable]:
with-block
with open('file_path') as file:
for line in file:
print(line)
可以编写一个类,用特殊的方法接入with语句,规范如下:
class TraceBlock:
def message(self, arg):
print('running', arg)
def __enter__(self):
print('starting with block')
return self
def __exit__(self, exc_type, exc_val, exc_tb):
if exc_type is None:
print('exited normally\n')
else:
print('raise an exception!', exc_type)
return False
# return True
def main():
with TraceBlock() as action:
action.message('test 1')
print('reached')
with TraceBlock() as action:
action.message('test 2')
raise TypeError
print('not reached')
if __name__ == "__main__":
main()
'''
输出:
Traceback (most recent call last):
File "D:/Pycharm/MyProjects/pythonException/With_Exception.py", line 26, in
main()
File "D:/Pycharm/MyProjects/pythonException/With_Exception.py", line 22, in main
raise TypeError
TypeError
starting with block
running test 1
reached
exited normally
starting with block
running test 2
raise an exception!
'''
class TraceBlock:
def message(self, arg):
print('running', arg)
def __enter__(self):
print('starting with block')
return self
def __exit__(self, exc_type, exc_val, exc_tb):
if exc_type is None:
print('exited normally\n')
else:
print('raise an exception!', exc_type)
# return False
return True
def main():
with TraceBlock() as action:
action.message('test 1')
print('reached')
with TraceBlock() as action:
action.message('test 2')
raise TypeError
print('not reached')
if __name__ == "__main__":
main()
'''
输出:
starting with block
running test 1
reached
exited normally
starting with block
running test 2
raise an exception!
'''
I = IndexError('abc')
I.args
raise IndexError('abc')
class E(Exception): pass
def main():
try:
raise E('abc', 'def')
except E as X:
print(X.args) # ('abc', 'def')
if __name__ == "__main__":
main()
class E(Exception):
def __str__(self):
return 'Exception E occurs!'
def main():
try:
raise E('abc', 'def')
except E as X:
print(X.args)
print(X)
if __name__ == "__main__":
main()
'''
输入:
('abc', 'def')
Exception E occurs!
'''
class FormatError(Exception):
logfile = 'error_log.txt'
def __init__(self, line, file):
self.line = line
self.file = file
def logerror(self):
log = open(self.logfile, 'a+')
print('Error at', self.file, self.line, file=log)
def parser():
raise FormatError(40, 'error.txt')
def main():
try:
parser()
except FormatError as exc:
exc.logerror()
执行后,可见工程目录下新建了error.txt,其中内容如下:
Error at error.txt 40
截止文篇博文,Python基础与拾遗和Python进阶与拾遗一共17讲的内容就告一段落了。在阅读完毕这两部分后,就可以结合Python语言独有的技巧,进行面向对象的Python工程编写了。这也是笔者对Python语言相关技术的总结与复盘,希望能在未来推出更多技术干货,与各位读者朋友共同成长。
呈上Python进阶与拾遗前7讲链接:
Python进阶与拾遗1:Python中的模块
Python进阶与拾遗2:Python中的包
Python进阶与拾遗3:Python中的类
Python进阶与拾遗4:Python中的运算符重载
Python进阶与拾遗5:Python中的新式类
Python进阶与拾遗6:Python中的静态方法与类方法
Python进阶与拾遗7:Python中的装饰器
欢迎阅读笔者后续博客,各位读者朋友的支持与鼓励是我最大的动力!
written by jiong
君问归期未有期,
巴山夜雨涨秋池。
何当共剪西窗烛,
却话巴山夜雨时。