建立网站最好的模板,新公司网站建设都有哪些优势,绍兴市住房和城乡建设局官方网站,短网址生成器是什么意思Python用异常对象来表示异常情况#xff0c;如果异常对象未被处理或捕捉#xff0c;程序就会回溯#xff08;traceback#xff09;中止执行。 异常可以在出错时自动引发#xff0c;也可以主动引发。 异常被引发后如果不被处理就会传播至程序调用的地方#xff0c;直到主程…Python用异常对象来表示异常情况如果异常对象未被处理或捕捉程序就会回溯traceback中止执行。 异常可以在出错时自动引发也可以主动引发。 异常被引发后如果不被处理就会传播至程序调用的地方直到主程序全局作用域如果主程序仍然没有异常处理程序会带着栈跟踪终止。 raise引发异常 raise Exception
Traceback (most recent call last):File pyshell#1, line 1, in moduleraise Exception
Exception raise Exception(error!!!) Traceback (most recent call last): File pyshell#2, line 1, in module raise Exception(error!!!) Exception: error!!! 常见内建异常类 类名描述Exception所有异常的基类AttributeError特性引用或赋值失败时引发IOError试图打开不存在文件包括其他情况时引发IndexError在使用序列中不存在的索引时引发KeyError使用映射中不存在的键引发NameError找不到名字变量时引发SyntaxError在代码为错误形式时引发TypeError在内建操作或者函数应用于错误类型的对象引发 ValueError在内建操作或者函数应用于正确的对象但是该对象使用不合适的值引发ZeroDivision在除法或者模除操作的第二个参数为0时引发 自定义异常类继承自Exception class DefException(Exception):pass 捕捉异常使用try/except语句实现 try: x int(input(The first num:))y int(input(The second num:))print(x/y)
except ZeroDivisionError:print(Error)The first num:5
The second num:0
Error try:x int(input(The first num:))y int(input(The second num:))print(x/y)
except ZeroDivisionError:print(Error)
except ValueError:print(TypeError)The first num:5
The second num:o
TypeError 用一个块捕捉多个异常 try:x int(input(The first num:))y int(input(The second num:))print(x/y)
except (ZeroDivisionError,ValueError):print(Error)The first num:5
The second num:0
Error 捕捉对象 try:x int(input(The first num:))y int(input(The second num:))print(x/y)
except (ZeroDivisionError,ValueError) as e:print(e)The first num:5
The second num:0
division by zero 捕捉所有异常 try:x int(input(The first num:))y int(input(The second num:))print(x/y)
except:print(some errors)
The first num:5
The second num:
some errors 这种方式会捕捉用户中止执行的企图会隐藏所有程序员未想到并且未做好准备的错误。 对于异常情况进行处理 #在输入不合法时循环直到合法值出现退出循环
while True:try:x int(input(The first num:))y int(input(The second num:))print(x/y)except:print(Error)else:break#运行结果The first num:5
The second num:0
Error
The first num:6
The second num:3
2.0 finally子句用在可能的异常后进行清理不管是否有异常都要执行。在同一个try语句中不可以和except使用。 x None
try:x 1/0
finally:print(cleaning)del x#结果
cleaning
Traceback (most recent call last):File input.py, line 4, in modulex 1/0
ZeroDivisionError: division by zero***Repl Closed*** 可以在一条语句中组合使用tryexceptelsefinally try:x 1/0else:print(done)
finally:print(cleaning)#运行结果
cleaning***Repl Closed*** 转载于:https://www.cnblogs.com/HJhj/p/7423454.html