python 异常捕获 多重_python_异常处理

本文详细介绍了Python的异常处理机制,包括try-except、多个except代码块、多重异常捕获、try-except语句嵌套以及使用finally释放资源。通过实例展示了如何处理ZeroDivisionError和ValueError异常,并自定义异常类提升错误提示的可读性。
摘要由CSDN通过智能技术生成

1.除数为0的异常处理

i=input('请输入数字: ')

n=888

try:

result=n/int(i)

print(result)

print('{0}除以{1}等于{2}'.format(n,i,result))

except ZeroDivisionError as e:

print('不能除以0,异常{}'.format(e))

2.多个except代码块

i=input('请输入数字: ')

n=888

try:

result=n/int(i)

print(result)

print('{0}除以{1}等于{2}'.format(n,i,result))

except ZeroDivisionError as e:

print('不能除以0,异常{}'.format(e))

except ValueError as e:

print("输入的是无效数字,异常:{}".format(e))

3.多重异常捕获

i=input('请输入数字: ')

n=888

try:

result=n/int(i)

print(result)

print('{0}除以{1}等于{2}'.format(n,i,result))

except (ZeroDivisionError,ValueError) as e:

print('异常{}'.format(e))

4.try-except语句嵌套

#coding=utf-8

i=input("请输入数字: ")

n=8888

try:

i2=int(i)

try:

result=n/i2

print("{0}除以{1}等于{2}".format(n,i2,result))

except ZeroDivisionError as e1:

print("不能除以0,异常:{}".format(e1))

except ValueError as e2:

print("输入的是无效数字,异常:{}".format(e2))

5.使用finally代码块释放资源

i=input('请输入数字: ')

n=888

try:

result=n/int(i)

print(result)

print('{0}除以{1}等于{2}'.format(n,i,result))

except ZeroDivisionError as e:

print('不能除以0,异常{}'.format(e))

except ValueError as e:

print("输入的是无效数字,异常:{}".format(e))

finally:

print('资源释放')

6.自定义异常类

class TestException(Exception):

def __init__(self,message):

super().__init__(message)

i=input('请输入数字: ')

n=888

try:

result=n/int(i)

print(result)

print('{0}除以{1}等于{2}'.format(n,i,result))

except ZeroDivisionError as e:

#print('不能除以0,异常{}'.format(e))

raise TestException('不能除以0')

except ValueError as e:

#print("输入的是无效数字,异常:{}".format(e))

raise TestException('输入的是无效数字')

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值