python 26 -- python主要的内置异常及其处理


更全一点的预定义介绍

所有的预定义异常

在 python 中,常见的异常都已经预定义好了,在交互式环境中,用 dir(__builtins__)命令就会显示出所有的预定义异常。

>>> dir(__builtins__)
['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BlockingIOError', 'BrokenPipeError', 'BufferError', 'BytesWarning', 'ChildProcessError', 'ConnectionAbortedError', 'ConnectionError', 'ConnectionRefusedError', 'ConnectionResetError', 'DeprecationWarning', 'EOFError', 'Ellipsis', 'EnvironmentError', 'Exception', 'False', 'FileExistsError', 'FileNotFoundError', 'FloatingPointError', 'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError', 'ImportWarning', 'IndentationError', 'IndexError', 'InterruptedError', 'IsADirectoryError', 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'ModuleNotFoundError', 'NameError', 'None', 'NotADirectoryError', 'NotImplemented', 'NotImplementedError', 'OSError', 'OverflowError', 'PendingDeprecationWarning', 'PermissionError', 'ProcessLookupError', 'RecursionError', 'ReferenceError', 'ResourceWarning', 'RuntimeError', 'RuntimeWarning', 'StopAsyncIteration', 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'TimeoutError', 'True', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning', 'ValueError', 'Warning', 'ZeroDivisionError', '__build_class__', '__debug__', '__doc__', '__import__', '__loader__', '__name__', '__package__', '__spec__', 'abs', 'all', 'any', 'ascii', 'bin', 'bool', 'breakpoint', 'bytearray', 'bytes', 'callable', 'chr', 'classmethod', 'compile', 'complex', 'copyright', 'credits', 'delattr', 'dict', 'dir', 'divmod', 'enumerate', 'eval', 'exec', 'exit', 'filter', 'float', 'format', 'frozenset', 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex', 'id', 'input', 'int', 'isinstance', 'issubclass', 'iter', 'len', 'license', 'list', 'locals', 'map', 'max', 'memoryview', 'min', 'next', 'object', 'oct', 'open', 'ord', 'pow', 'print', 'property', 'quit', 'range', 'repr', 'reversed', 'round', 'set', 'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'vars', 'zip']

常用的预定义异常

常用的预定异常名及其描述如下表:

异常名 描述
AttributeError 调用不存在的方法引发的异常
EOFError 遇到文件末尾引发的异常
ImportError 导入模块出错引发的异常
IndexError 列表越界引发的异常
IOError I/O操作引发的异常,如打开文件出错等
KeyError 使用字典中不存在的关键字引发的异常
NameError 使用不存在的变量名引发的异常
TabError 语句块缩进不正确引发的异常
ValueError 搜索列表中不存在的值引发的异常
ZeroDivisionError 除数为0引发的异常

处理

except 语句主要有以下几种用法:

  • 捕获所有异常
except:
  • 捕获指定异常
except <异常名>:
  • 捕获异常名 1 或异常名 2
except (异常名 1, 异常名 2):
  • 捕获指定异常及其附加的数据
except <异常名> as <数据>:

捕获异常名 1 或者异常名 2 及异常的附加数据

except (异常名 1, 异常名 2) as <数据>:
示例

源代码如下:两个函数分别是捕获所有异常只是捕获越界异常

# -*- coding:utf-8 -*-
def testTryAll(index,i):
	warlst = ['Texas','Irelia','Diana']
	try:
		print(len(warlst[index])/i)
	except:					# 捕获所有异常
		print('ERROR!')

def testTryOne(index,i):
        warlst = ['Texas','Irelia','Diana']
        try:
                print(len(warlst[index])/i)
        except IndexError:
                print('ERROR!')

print('Try all...Right')
testTryAll(1,2)
print('Try all...one Error')			# 发生除0异常
testTryAll(1,0)
print('Try all...two Error')			# 越界异常和除0异常同时发生
testTryAll(4,0)
print(' ')
print('Try one...right')
testTryOne(1,2)
print('Try one...one Error')
testTryOne(4,2)
print('Try one...one Error')
testTryOne(1,0)

结果如下:(Terminal,MacOS Catalina)

Try all...Right
3.0
Try all...one Error
ERROR!
Try all...two Error
ERROR!
 
Try one...right
3.0
Try one...one Error
ERROR!
Try one...one Error
Traceback (most recent call last):
  File "Try.py", line 28, in <module>
    testTryOne(1,0)
  File "Try.py", line 12, in testTryOne
    print(len(warlst[index])/i)
ZeroDivisionError: division by zero

或者(我也不知道为什么两个输出len一个是浮点数一个整数)(VScode,MacOS Catalina)

Try all...Right
3
Try all...one Error
ERROR!
Try all...two Error
ERROR!
 
Try one...right
3
Try one...one Error
ERROR!
Try one...one Error
Traceback (most recent call last):
  File "/Users/stark/Desktop/Try.py", line 28, in <module>
    testTryOne(1,0)
  File "/Users/stark/Desktop/Try.py", line 12, in testTryOne
    print(len(warlst[index])/i)
ZeroDivisionError: integer division or modulo by zero
发布了64 篇原创文章 · 获赞 6 · 访问量 5547

猜你喜欢

转载自blog.csdn.net/weixin_45494811/article/details/104203134
今日推荐