python 异常

python 异常

1.异常

异常就是程序运行时发生错误的信号(在程序出现错误时,则会产生一个异常,若程序没有处理它,则会抛出该异常,程序的运行也随之终止)

Traceback (most recent call last):
  File "C:/Disk_D/pycharm_stu/macboy/python3_sutdy_notepad/test.py", line 3, in <module>
    fdfs
NameError: name 'fdfs' is not defined

# 异常类 NameError
# 异常值 name 'fdfs' is not defined
# 异常追踪信息 Traceback。。。

2.异常种类

# 异常种类
AttributeError 试图访问一个对象没有的树形,比如foo.x,但是foo没有属性x
IOError 输入/输出异常;基本上是无法打开文件
ImportError 无法引入模块或包;基本上是路径问题或名称错误
IndentationError 语法错误(的子类) ;代码没有正确对齐
IndexError 下标索引超出序列边界,比如当x只有三个元素,却试图访问x[5]
KeyError 试图访问字典里不存在的键
KeyboardInterrupt Ctrl+C被按下
NameError 使用一个还未被赋予对象的变量
SyntaxError Python代码非法,代码不能编译(个人认为这是语法错误,写错了)
TypeError 传入对象类型与要求的不符合
UnboundLocalError 试图访问一个还未被设置的局部变量,基本上是由于另有一个同名的全局变量,导致你以为正在访问它
ValueError 传入一个调用者不期望的值,即使值的类型是正确的

更多:
ArithmeticError
AssertionError
AttributeError
BaseException
BufferError
BytesWarning
DeprecationWarning
EnvironmentError
EOFError
Exception
FloatingPointError
FutureWarning
GeneratorExit
ImportError
ImportWarning
IndentationError
IndexError
IOError
KeyboardInterrupt
KeyError
LookupError
MemoryError
NameError
NotImplementedError
OSError
OverflowError
PendingDeprecationWarning
ReferenceError
RuntimeError
RuntimeWarning
StandardError
StopIteration
SyntaxError
SyntaxWarning
SystemError
SystemExit
TabError
TypeError
UnboundLocalError
UnicodeDecodeError
UnicodeEncodeError
UnicodeError
UnicodeTranslateError
UnicodeWarning
UserWarning
ValueError
Warning
ZeroDivisionError

3.异常处理

python解释器检测到错误,触发异常

为了保证程序的健壮性与容错性,即在遇到错误时程序不会崩溃,我们需要对异常进行处理


age = input(">>:")
if age.isdigit():
int(age)
elif age.isspace():
print("空格")
elif len(age) == 0:
print("空值")
else:
print("未知")

print(age)
 
def test():
print("test running")


choice_dict = {
"1": "admin",
"2": "guest"
}

while True:
test()
choice = input("权限:").strip()
if choice in choice_dict:
print(choice_dict[choice])
break
if not choice or choice not in choice_dict: continue


#
基本语法为 try: 被检测的代码块 except 异常类型: try中一旦检测到异常,就执行这个位置的逻辑 #举例 try: f=open('a.txt') g=(line.strip() for line in f) print(next(g)) print(next(g)) print(next(g)) print(next(g)) print(next(g)) except StopIteration: f.close()

4.else finally assert

"""
错误有两种:
1.语法错误
def f:
    pass
2.逻辑错误
age= input()  # 输入 'fddfs'
age = int(age)

异常:程序运行过程中发生的错误信号 有三部分组成
1.Traceback 追踪信息
2.NameError 错误类型
3.错误的值
"""
try:
    num = 10
    int(num)
    # int("dsfd")
    choice_dict["1fd"]

except Exception as e:
    print(e)
else:
    print('try内代码块没有异常则执行')
finally:
    print('finally无论是否有异常,则都会执行')

# 自定义异常
# class SetException(BaseException):
#     def __int__(self,msg):
#         self.msg = msg
# print(SetException('自定义异常'))

# 断言 assert 条件

r = 1
# assert r == 2  # 判断结果是false则抛出异常 AssertionError

参考:http://www.cnblogs.com/linhaifeng/articles/6232220.html