Python 中的异常处理

本文介绍了Python中的三种异常处理方式:try...except...finally结构、assert断言及raise语句的使用方法。通过实例展示了如何捕获和处理除零错误、自定义错误消息,并通过循环示例说明了raise语句的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Python 中内置了多种异常处理方式。

1 try····except···

a = 10
b = 0
try:
    i = a/b
except Exception, e:
    print e

>>> integer division or modulo by zero
# 先执行try语句块的内容,若能正常执行,则略过except内容;
# 若try语句块不能正常运行,则紧跟着执行except语句块内容;
a = 10
b = 0
try:
    i = a/b
except Exception, e:
    print e
finally:
    print 101
>>> integer division or modulo by zero
   101
# 先执行try语句块的内容,若能正常执行,则略过except内容;
# 若try语句块不能正常运行,则紧跟着执行except语句块内容;
# 最后执行finally语句块;(无论try模块是否正常运行,finally语句块都要执行)

 2 assert 语句

>>> assert 3>2, 'error'
>>> 
# 3>2 等式成立,不返回任何结果

>>> assert 1>2, 'error'
Traceback (most recent call last):
  File "C:\Users\Administrator\Desktop\xy.py", line 1, in <module>
    assert 1>2, 'error'
AssertionError: error
# 1>2 等式不成立,抛出异常

 3 raise 语句

>>> for i in range(5):
         if i == 2:
            raise ValueError #(ValueError是系统规定的错误类型)
      # raise Exception(‘i == 2’) #抛出自定义的错误类型
        else:
            print i

0
1

Traceback (most recent call last):
  File "C:\Users\Administrator\Desktop\xy.py", line 4, in <module>
    raise ValueError
ValueError

'''
0
1

Traceback (most recent call last):
  File "C:\Users\Administrator\Desktop\xy.py", line 4, in <module>
    raise Exception('i==2')
Exception: i==2
'''

 

转载于:https://www.cnblogs.com/wangyueyouyi/p/9591376.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值