python异常

异常追踪的信息说明
异常类

try:
#引发异常的代码
excep (异常类1,异常类2,...,异常类n) as 异常值:
#捕作异常后,执行此语句块,没捕作到向上传播,直到主程序终止并显示跟踪消息
else:
#try下语句块没有异常错误,执行此语句块
finally:
#不管有没有引发异常,ecpect有没有捕作到异常,都执行此语句块

不能有try....else...组合,其它都行
except Exception : #这表示能捕捉到Exception及其派生子类的异常
except:   #这表示能捕捉到所有异常

raise

>>raise Exception
Traceback (most recent call last):

  File "<ipython-input-9-2aee0157c87b>", line 1, in <module>
    raise Exception

Exception
###只抛出了异常类

>>raise Exception('异常值')
Traceback (most recent call last):

  File "<ipython-input-10-54f75181d10a>", line 1, in <module>
    raise Exception('异常值')

Exception: 异常值
#有异常类,也有值

def faulty():
    raise Exception('Something is wrong')
        
def ignore_exception():
    faulty()
    
def handle_exception():
    try:
        faulty()
    except:
        print('Exception handled')

>>ignore_exception()
Traceback (most recent call last):

  File "<ipython-input-27-c68afa428f2b>", line 14, in <module>
    ignore_exception()

  File "<ipython-input-27-c68afa428f2b>", line 5, in ignore_exception
    faulty()

  File "<ipython-input-27-c68afa428f2b>", line 2, in faulty
    raise Exception('Something is wrong')

Exception: Something is wrong

>>handle_exception()
Exception handled

#faulty中引发的异常依次从faulty和ignore_exception向外传播,最终显示一条跟踪消息。
#调用handle_exception时,异常最终传播到handle_exception,并被这里的try/except语句处理
try:
    1/0
except ZeroDivisionError:
    raise

Traceback (most recent call last):

  File "<ipython-input-19-60d1e40b6850>", line 2, in <module>
    1/0

ZeroDivisionError: division by zero    

#捕获异常后,如果要继续引发它(即继续向上传播),可调用raise且不提供任何参数

try:
    1/0
except ZeroDivisionError:
    raise ValueError

Traceback (most recent call last):

  File "<ipython-input-20-1646f08782cb>", line 5, in <module>
    raise ValueError

ValueError

assert 表达式 [, 参数]

age = 10
>>assert 0<age<100
>>assert 0<age<100,''The age must be realistic'
#表达式为True,不返回任何信息

age = -1
>>assert 0<age<100
Traceback (most recent call last):

  File "<ipython-input-25-76d3ffa0ff69>", line 1, in <module>
    assert 0<age<100

AssertionError

>>assert 0<age<100,'The age must be realistic'
Traceback (most recent call last):

  File "<ipython-input-26-19da6d03734e>", line 1, in <module>
    assert 0<age<100,'The age must be realistic'

AssertionError: The age must be realistic
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值