日记大全

日记大全 > 句子大全

python异常处理语句

句子大全 2023-06-30 04:10:01
相关推荐

一,异常处理

1,异常:在语法上是正确的,但在尝试执行时,仍然会引起某种错误

如1/0

2,常见的内置异常

NameError:尝试访问一个没有声明的变量

ZeroDivision​Error:除数为0

indexError:索引超过序列范围

KeyError:请求一个不存在的字典的键

IOError:输入\输出错误

AttributeError:尝试访问未知的对象属性

3,异常处理语句

第一种:如果有异常,就执行except分支

try:

(do something)

except[tuple of exception]:

(other thing)

实例:

while True:

try:

x=int(input("input an int:"))

r=10/x

print(r)

except ZeroDivision​Error:

print("you should not input zero")

break

except SyntaxError:

print("input a number")

第二种:第一种情况下,再如果没有异常就执行else分支

try:

(do something)

except[tuple of exception]:

(other thing)

else:

(something)

第三种:第二种基础上,不管是否有异常,finnally都执行

try:

(do something)

except[tuple of exception]:

(other thing)

else:

(something)

finnally:

(something)

如:

while True:

try:

x=int(input("input an int:"))

r=10/x

print(r)

except ZeroDivision​Error:

print("you should not input zero")

break

finally:

print("goodbye")

break

注意:else和finnally均可选择要或不要

4,raise和assert

抛出异常:raise语句允许强制发生指定的异常

>>> try:

... raise NameError("python")

... except NameError:

... print("-----")

... raise

...

-----

Traceback (most recent call last):

File "<stdin>", line 2, in <module>

NameError: python

断言:assert语句,发起条件判断

>>> x=-2

>>> assert x<0

>>> assert x>0

Traceback (most recent call last):

File "<stdin>", line 1, in <module>

Assertion​Error

实例:

while True:

try:

age=int(input("how old are you:"))

assert age>0

if age>150:

raise ValueError("are you a god?")

elif (age<=150)and(age>0):

print("right age")

except(ValueError,Assertion​Error):

print("find your glasses.")

break

阅读剩余内容
网友评论
相关内容
拓展阅读
最近更新