python 异常处理

异常处理格式:

    try:
        expression
    except:
        expression
    finally:
        expression
        

使用 traceback 输出异常

示例打印异常信息:

import traceback

if __name__ == '__main__':
    try:
        i = 0
        print(10 / i)
    except:
        error = traceback.format_exc()
        print(error)
    print('程序没有crash')

输出如下:

下面输出异常信息:
Traceback (most recent call last):
  File "/Users/my/workspace/z_study/Python/teach/基础/异常处理.py", line 6, in <module>
    print(10 / i)
ZeroDivisionError: division by zero

程序没有crash

Process finished with exit code 0

输入出异常中的消息

示例打印异常信息

if __name__ == '__main__':
    i = 0
    try:
        print(10 / i)
    except Exception as e:
        print('下面输出异常信息:')
        print(e)
    print('程序没有crash')

输出如下:

下面输出异常信息:
division by zero
程序没有crash

Process finished with exit code 0

主动抛出一个异常

python中使用 raise 抛出异常,等同于java中的 throw

if __name__ == '__main__':
    i = 0
    try:
        raise Exception('test error')
    except Exception as e:
        print('下面输出异常信息:')
        print(e)
    print('程序没有crash')

运行结果:

下面输出异常信息:
test error
程序没有crash

自定义异常

所有异常都继承自BaseException,一般我们自定义异常,继承自Exception就行:

class TestException(Exception):
    def __init__(self):
        super().__init__(self, 'this is a test exception')


if __name__ == '__main__':
    try:
        raise TestException()
    except Exception as e:
        print('下面输出异常信息:')
        print(e)
    print('程序没有crash')

运行结果:

下面输出异常信息:
(TestException(...), 'this is a test exception')
程序没有crash
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容