Python学习VII --- 异常处理

本文介绍了Python中的异常处理机制,包括try...except...等结构的使用方法,并演示了如何通过raise重新抛出异常。此外,还提供了自定义异常类的示例。

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

这篇博客主要是阅读python之旅 时做的笔记。提取出最主要的知识点,供个人在以后中快速查阅。

常见组合

try...except...
try...except...else...
try...except...else...finally...
try...except...except...else...finally...
try...finally...
try:
    x = input('Enter x: ')
    y = input('Enter y: ')
    print x / y
except ZeroDivisionError as e:
    print 'ZeroDivisionError:',e
except TypeError as e:
    print 'TypeError:',e
except BaseException as e:    # 捕获其他异常
    print 'BaseException:',e
else:                 # 当没有异常时,执行else
    print 'no error!'

因为BaseException是所有异常的父类。

  • Finally
try:
    x = 1/0
    print x
finally:            # 不管三七二十一,这个都要执行
    print 'DONE'

raise异常

有时候捕获了异常,还想再把异常抛出去。

try:
    x = input('Enter x: ')
    y = input('Enter y: ')
    print x / y
except ZeroDivisionError as e:
    print 'ZeroDivisionError:',e
except TypeError as e:
    print 'TypeError:',e
except BaseException as e:
    print 'BaseException:',e
    raise                           # 使用 raise 抛出异常,不用带参数
else:
    print 'no error!'

print 'hello world'

Exception类 — 自定义异常类

# 自定义异常类
class SomeError(Exception):
    pass

try:
    x = input('Enter x: ')
    y = input('Enter y: ')
    print x / y
except ZeroDivisionError as e:
    print 'ZeroDivisionError:',e
except TypeError as e:
    print 'TypeError:',e
except BaseException as e:
    print 'BaseException:',e
    raise SomeError('invalid value')    # 抛出自定义的异常
else:
    print 'no error!'

print 'hello world'


Enter x: 
BaseException: unexpected EOF while parsing (<string>, line 0)
----------------------------------------------------------------------
SomeError                            Traceback (most recent call last)
<ipython-input-20-66060b472f91> in <module>()
     12 except BaseException as e:
     13     print 'BaseException:',e
---> 14     raise SomeError('invalid value')
     15 else:
     16     print 'no error!'

SomeError: invalid value
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值