[TOC]
异常名 | 释义 |
---|---|
AssertError | 断言语句(assert)失败 |
AttributeError | 尝试访问未知的对象属性 |
EOFError | 用户输入文件末尾标志 EOF(Ctrl+d) |
FloatingPointError | 浮点计算错误 |
GeneratorExit | generator.close() 方法被调用的时候 |
ImportError | 导入模块失败的时候 |
IndexError | 索引超出序列的范围 |
KeyError | 字典中查找一个不存在的关键字 |
KeyboardInterrupt | 用户输入中断键 (Ctrl+c) |
MemoryError | 内存溢出(可通过删除对象释放内存) |
NameError | 尝试访问一个不存在的变量 |
NotImplementedError | 尚未实现的方法 |
OSError | 操作系统产生的异常(例如打开一个不存在的文件) |
OverflowError | 数值运算超出最大限制 |
ReferenceError | 弱引用 (weak reference) 试图访问一个已经被垃圾回收机制回收了的对象 |
RuntimeError | 一般的运行时错误 |
StopIteration | 迭代器没有更多的值 |
SyntaxError | Python 的语法错误 |
IndentationError | 缩进错误 |
TabError | Tab 和空格混合使用 |
SystemError | Python 编译器系统错误 |
SystemExit | Python 编译器进程被关闭 |
TypeError | 不同类型间的无效操作 |
UnboundLocalError | 访问一个未初始化的本地变量(NameError 的子类) |
UnicodeError | Unicode 相关的错误(ValueError 的子类) |
UnicodeEncodeError | Unicode 编码时的错误(UnicodeError 的子类) |
UnicodeDecodeError | Unicode 解码时的错误(UnicodeError 的子类) |
UnicodeTranslateError | Unicode 转换时的错误(UnicodeError 的子类) |
ValueError | 传入无效的参数 |
ZeroDivisionError | 除数为零 |
>>> num = int(input("Please enter a number: "))
Please enter a number: 0
>>> 100 / num
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ZeroDivisionError: division by zero
>>>
try:
尝试实现某个操作,
如果没出现异常,任务就可以完成
如果出现异常,将异常从当前代码块扔出去尝试解决异常
(个人觉得,这里有点像 switch-case)
except 异常类型1:
解决方案1:用于尝试在此处处理异常解决问题
except 异常类型2:
解决方案2:用于尝试在此处处理异常解决问题
except (异常类型1, 异常类型2, ...):
解决方案:针对多个异常使用相同的处理方式
excpet:
解决方案:所有异常的解决方案
else:
如果没有出现任何异常,将会执行此处代码
finally:
管你有没有异常都要执行的代码
try:
divisor = int(input("Plz input the divisor: "))
rst = 100 / divisor
print(f">>> rst = {rst}")
except:
print("Illegal input! Please try again!")
# exit()
>>>
$ python .\try-except_01.py
Plz input the divisor: 0
Illegal input! Please try again!
try:
divisor = int(input("Plz input the divisor: "))
rst = 100 / divisor
print(f">>> rst = {rst}")
except ZeroDivisionError as e:
print("Illegal input! The reasons for the error are: ")
print(e)
>>>
$ python .\try-except_02.py
Plz input the divisor: 0
Illegal input! The reasons for the error are:
division by zero
try:
divisor = int(input("Plz input the divisor: "))
rst = 100 / divisor
print(f">>> rst = {rst}")
except ZeroDivisionError as e:
print("ZeroDivisionError!")
print(e)
except NameError as e:
print("NameError!")
print(e)
except Exception as e:
print("The reasons for the error are: ")
print(e)
except ValueError as e:
print("This sentence will not be executed!")
>>>
$ python .\try-except_03.py
Plz input the divisor: abc
The reasons for the error are:
invalid literal for int() with base 10: ‘abc‘
try:
print("No Error.")
except NameError:
print("NameError!")
else:
print("Any Error?")
>>>
$ python .\try-except_04.py
No Error.
Any Error?
try:
print("Let me throw an exception!")
raise ValueError
print("You can‘t see me.")
except NameError:
print("NameError!")
except ValueError:
print("ValueError!")
except Exception as e:
print("The reasons for the error are: ")
print(e)
finally:
print("This sentence will certainly be carried out!")
>>>
$ python .\try-except_05.py
Let me throw an exception!
ValueError!
This sentence will certainly be carried out!
class MyValueError(ValueError):
pass
try:
print("Let me throw an exception!")
raise MyValueError
print("You can‘t see me.")
except NameError:
print("NameError!")
except ValueError:
print("ValueError!")
except Exception as e:
print("The reasons for the error are: ")
print(e)
finally:
print("This sentence will certainly be carried out!")
>>>
$ python .\try-except_06.py
Let me throw an exception!
ValueError!
This sentence will certainly be carried out!
In [1]: pritn()
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-1-b44a7e815a2a> in <module>()
----> 1 pritn()
NameError: name ‘pritn‘ is not defined
def func(nums):
n = len(nums)
i, t, s = 0, -6, 0 # idx, tmp, sum
while i < n:
try:
t = nums.index(13, t+6)
s += sum(nums[i:t])
i = t + 6
except ValueError:
return s + sum(nums[i:])
return s
if __name__ == "__main__":
nums1 = [1, 2, 3]
nums2 = [1, 2, 13, 4, 5, 6, 7, 8, 9]
nums3 = [1, 2, 13, 4]
print(func([])) # 0
print(func(nums1)) # 6
print(func(nums2)) # 12
print(func(nums3)) # 3
原文:https://www.cnblogs.com/yorkyu/p/12056532.html