2020-08-27

try……except使用

while True:
try:
x=int(input(“请输入一个数字:”))
print(“输入的数字为:”,x)
if x==88:
print(“退出程序”)
break
except BaseException as e:
print(e)
print(“异常,输入的不是数字”)
print(“循环数字程序结束”)

请输入一个数字:12
输入的数字为: 12
请输入一个数字:qq
invalid literal for int() with base 10: ‘qq’
异常,输入的不是数字
请输入一个数字:88
输入的数字为: 88
退出程序
循环数字程序结束

try:
a=input(“请输入一个被除数:”)
b=input(“请输入一个除数:”)
c=float(a)/float(b)
print©
except ZeroDivisionError:
print(“异常,除数不能为0”)
except ValueError:
print(“异常,不能将字符型转化为数字”)
except NameError:
print(“异常,变量不存在”)
except BaseException as e:
print(“e”)

 except……else

try:
a=input(“请输入一个被除数:”)
b=input(“请输入一个除数:”)
c=float(a)/float(b)
except BaseException as e:
print(e)
else:
print©
print(“程序结束”)

try:
f=open(“d:/s.txt”,“r”)
content=f.readline()
print(content)
except:
print(“文件未找到”)
finally:
print(“关闭文件”)
try:
f.close()
except BaseException as e:
print(e)
print(“程序结束”)

文件未找到
关闭文件
name ‘f’ is not defined
程序结束

SyntaxError 语法错误
NameError 尝试访问一个没有声明的变量
ZeroDivisionError 除数为0错误
ValueError 数值错误
TypeError 类型错误
AttributeError 访问对象不存在属性
IndexError 索引越界异常
KeyError 字典的关键子不存在

finally无论是否发生异常都会执行
With代码不论是否有异常,总能保证资源正常释放。

with open(“d:/a.txt”,“r”) as f:
content=f.readline()
print(content)

print(“程序结束”)

    traceback异常位置

import traceback
try:
print(“step1”)
num=1/0
except:
traceback.print_exc()

import traceback
try:
print(“step1”)
num=1/0
except:
with open(“d:/a.txt”,“a”) as f:
traceback.print_exc(file=f)

raise抛出异常

class AgeError(Exception):
def init(self,errorinfo):
Exception.init(self)
self.errorinfo=errorinfo
def str(self):
return(str(self.errorinfo)+",年龄错误,请输入1到150之间的数")
if name==“main” :
age=int(input(“请输入一个年龄:”))
if age<1 or age>150:
raise AgeError(age)
else:
print(“正常年龄为:”,age)

请输入一个年龄:210
Traceback (most recent call last):
File “C:/Users/Administrator/PycharmProjects/untitled2/22.py”, line 10, in
raise AgeError(age)
main.AgeError: 210,年龄错误,请输入1到150之间的数

Process finished with exit code 1

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值