Python 学习笔记16 异常处理

我们在编码的过程中,难免会遇到一些错误和异常, 这时候程序会异常退出,并且会抛出错误信息:

比如:

 

print(1/0)

'''
输出:
Traceback (most recent call last):
  File "D:/PythonStudy/errors.py", line 3, in <module>
    print(1/0)
ZeroDivisionError: division by zero
'''

 

我们尝试让1 去除0,结果系统报错了异常  ‘ZeroDivisionError: division by zero’, 表示不能被零除。

Python内置许多异常,当出现这些问题时,会提示我们并中断运行,python3.7中主要有以下的异常:

BaseException
 +-- SystemExit
 +-- KeyboardInterrupt
 +-- GeneratorExit +-- Exception +-- StopIteration +-- StopAsyncIteration +-- ArithmeticError | +-- FloatingPointError | +-- OverflowError | +-- ZeroDivisionError +-- AssertionError +-- AttributeError +-- BufferError +-- EOFError +-- ImportError | +-- ModuleNotFoundError +-- LookupError | +-- IndexError | +-- KeyError +-- MemoryError +-- NameError | +-- UnboundLocalError +-- OSError | +-- BlockingIOError | +-- ChildProcessError | +-- ConnectionError | | +-- BrokenPipeError | | +-- ConnectionAbortedError | | +-- ConnectionRefusedError | | +-- ConnectionResetError | +-- FileExistsError | +-- FileNotFoundError | +-- InterruptedError | +-- IsADirectoryError | +-- NotADirectoryError | +-- PermissionError | +-- ProcessLookupError | +-- TimeoutError +-- ReferenceError +-- RuntimeError | +-- NotImplementedError | +-- RecursionError +-- SyntaxError | +-- IndentationError | +-- TabError +-- SystemError +-- TypeError +-- ValueError | +-- UnicodeError | +-- UnicodeDecodeError | +-- UnicodeEncodeError | +-- UnicodeTranslateError +-- Warning +-- DeprecationWarning +-- PendingDeprecationWarning +-- RuntimeWarning +-- SyntaxWarning +-- UserWarning +-- FutureWarning +-- ImportWarning +-- UnicodeWarning +-- BytesWarning +-- ResourceWarning

 有关内置异常的详细描述可以参考python的相关文档,链接如下: https://docs.python.org/zh-cn/3/library/exceptions.html#bltin-exceptions

 

Python提供了一套方式,用来捕获和处理错误和异常:

使用try....except...finally来对可能存在的错误进行处理:

#-*- coding:utf-8 -*-

try:
    print(1/0)
except ZeroDivisionError:
    print('Can not division 0, happen ZeroDivisionError')
finally:
    print('Go to next step')

'''
输出:
Can not division 0, happen ZeroDivisionError
Go to next step
'''

 

通过上面的例子,我们可以看到,代码首先执行try里的code,如果遇到了指定的错误,那么就执行except中的代码, 处理完毕后执行finally中的代码。

在每个代码块中,支持各种判断和迭代,其工作的流程结构如下:

 

 除了系统内置的错误,我们也可以在代码中主动抛出一些错误:

#-*- coding:utf-8 -*-
name = 'ralf'
if name != 'rachel':
    raise Exception('The name is not ralf')

'''
输出:
Traceback (most recent call last):
  File "D:/PythonStudy/errors.py", line 4, in <module>
    raise Exception('The name is not ralf')
Exception: The name is not ralf
'''

 

我们也可以通过继承Exception base class,自定我们自己的错误类型:

#-*- coding:utf-8 -*-
class NameError(Exception):
    def __init__(self, level, message):
        self.level = level
        self.message = message
try:
    name = 'ralf'
    if name != 'rachel':
        raise NameError('Error', 'Name is not right')
except NameError as e:
    print(e.level)
    print(e.message)
'''
输出:
Error
Name is not right
'''

 

转载于:https://www.cnblogs.com/wanghao4023030/p/11221801.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值