不要让 except 裸奔!裸奔很爽,但有隐忧。
(本笔记适合学完 Python 五大基本数据类型,有了些 Python 基础的 coder 翻阅)
Python 官网:https://www.python.org/
Free:大咖免费“圣经”教程《 python 完全自学教程》,不仅仅是基础那么简单……
地址:https://lqpybook.readthedocs.io/
自学并不是什么神秘的东西,一个人一辈子自学的时间总是比在学校学习的时间长,没有老师的时候总是比有老师的时候多。
—— 华罗庚
本文质量分:
CSDN质量分查询入口:http://www.csdn.net/qc
我为图方便,一直在
try:
…
except Exception as error:
…
没有预见到那样做的隐忧。此后,一定谨记齐老教诲,Don’t “bare except”!(不要让 except 裸奔!)
只要代码有错误捕获,铁定要标明预见到的错误类型。
要了解 try … except …,不让 except 裸奔,我们得熟悉常见的 Python 错误/异常。下面,我们一起来了解 Python 的十大错误/异常——
例如——
>>> int(sorted)
Traceback (most recent call last):
File "" , line 1, in <module>
TypeError: int() argument must be a string, a bytes-like object or a real number, not 'builtin_function_or_method'
>>> tuple(45)
Traceback (most recent call last):
File "" , line 1, in <module>
TypeError: 'int' object is not iterable
>>> list(789)
Traceback (most recent call last):
File "" , line 1, in <module>
TypeError: 'int' object is not iterable
>>>
Convert a number or string to an integer, or return 0 if no arguments. (摘录 help(int) 文本 )
If no argument is given, the constructor returns an empty tuple.
If iterable is specified the tuple is initialized from iterable’s items.
If the argument is a tuple, the return value is the same object. (摘录 help(tuple) 文本 )
If no argument is given, the constructor creates a new empty list.
The argument must be an iterable if specified. (摘录 help(list) 文本 )
int('g')
ValueError: invalid literal for int() with base 10: ‘g’
如果 int 的参数是字符串,一定要是整型数字字符串,否则报 ValueError 。
如——
>>> print(name) # 变量 name 未定义
Traceback (most recent call last):
File "" , line 1, in <module>
NameError: name 'name' is not defined
>>>
>>> s = '索引错误:即引用索引超出索引范围。当尝试 访问列表、元组或字符串等序列中不存在的索引时引发。'
>>> len(s)
45
>>> s[45]
Traceback (most recent call last):
File "" , line 1, in <module>
IndexError: string index out of range
>>> lis = [2, 5, 8]
>>> lis[9]
Traceback (most recent call last):
File "" , line 1, in <module>
IndexError: list index out of range
>>> nums = 6, 8, 9, 56, 13
>>> type(nums)
<class 'tuple'>
>>> nums[99]
Traceback (most recent call last):
File "" , line 1, in <module>
IndexError: tuple index out of range
>>>
>>>
>>> {}[5]
Traceback (most recent call last):
File "" , line 1, in <module>
KeyError: 5
>>> d = {'d': 67, 'e': 99}
>>> d['a']
Traceback (most recent call last):
File "" , line 1, in <module>
KeyError: 'a'
>>> d.get('a')
>>> d.get('a', 'None')
'None'
>>> d.get('a', None)
>>> d.get('a', 0)
0
>>> type(d.get('a'))
<class 'NoneType'>
>>> str(d.get('a'))
'None'
>>>
如命令行模式试炼可见,引用不存在的字典 key 会报错 KeyError 。其实,字典不但可以 dict[key] 引用,也可以 dict.get(key) 引用 key 的 value 。后者引用不存在的 key ,不会报错,默认返回 None 。如果设置第二个参数,字典中有 key ,返回 key 的值;字典中无 key ,则返回第二个参数对象。
引用字典 key ,dict.get(key) 比 dict[key] 更适宜些。
>>>
>>> 5/0
Traceback (most recent call last):
File "" , line 1, in <module>
ZeroDivisionError: division by zero
>>> d = 5 - 5
>>> 6/d
Traceback (most recent call last):
File "" , line 1, in <module>
ZeroDivisionError: division by zero
>>>
Python 3.11.1 (main, Dec 7 2022, 05:56:18) [Clang 14.0.6 (https://android.googlesource.com/toolchain/llvm-project 4c603efb0 on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> open('file4.py')
Traceback (most recent call last):
File "" , line 1, in <module>
FileNotFoundError: [Errno 2] No such file or directory: 'file4.py'
>>>
我好纳闷了,IOError 到我的环境,怎么就变成了 FileNotFoundError ?
OS exceptions¶
The following exceptions are subclasses of OSError, they get raised depending on the system error code.
exception BlockingIOError
Raised when an operation would block on an object (e.g. socket) set for non-blocking operation. Corresponds to errno EAGAIN, EALREADY, EWOULDBLOCK and EINPROGRESS.
In addition to those of OSError, BlockingIOError can have one more attribute:
characters_written
An integer containing the number of characters written to the stream before it blocked. This attribute is available when using the buffered I/O classes from the io module. (摘录于 IOError 官方文档)
IOError 最新版本官方文档地址:https://docs.python.org/3.12/library/exceptions.html?highlight=ioerror#IOError
~ $ python
Python 3.11.1 (main, Dec 7 2022, 05:56:18) [Clang 14.0.6 (https://android.googlesource.com/toolchain/llvm-project 4c603efb0 on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import mymodule
Traceback (most recent call last):
File "" , line 1, in <module>
ModuleNotFoundError: No module named 'mymodule'
>>>
>>> import pandas
Traceback (most recent call last):
File "" , line 1, in <module>
ModuleNotFoundError: No module named 'pandas'
>>>
注: mymodule ,是没有定义的模块名称,也就是无中生有。pandas ,我的 Python 3.11.10 一直没有 pip install pandas 成功。
ImportError 在我的 Python 3.6.6 和 3.11.1 上,都是“ModuleNotFoundError” 了。
>>> >>> list.add() Traceback (most recent call last): File "" , line 1, in <module> AttributeError: type object 'list' has no attribute 'add'
>>> str.append()
Traceback (most recent call last):
File "" , line 1, in <module> AttributeError: type object 'str' has no attribute 'append'
>>> set.replace('d', '')
Traceback (most recent call last):
File "" , line 1, in <module> AttributeError: type object 'set' has no attribute 'replace'
>>> str.get('x', 0)
Traceback (most recent call last):
File "" , line 1, in <module>
AttributeError: type object 'str' has no attribute 'get'
>>> dict.join([])
Traceback (most recent call last):
File "" , line 1, in <module>
AttributeError: type object 'dict' has no attribute 'join'
>>>
>>>
>>> input('\n请输入:')
请输入:Traceback (most recent call last):
File "" , line 1, in <module>
KeyboardInterrupt
>>>
Python 除了上面的基本异常类型,还可以定义自己特有的异常类型。
class MyException(Exception):
def __init__(self, error_tip):
self.tip = error_tip
def __str__(self):
return self.tip
自定义异常类型,不同于 Python “官方”异常类型,是需要手动 raise 。设定触发条件,用 raise 关键字主动抛出自动义异常类型。
if __name__ == '__main__':
gray = '\033[2m' # 灰色。
blue = '\033[34;1m' # 亮蓝。
red = '\033[31m' # 红色。
nocolor = '\033[0m' # 还原 python 默认配色。
print(f"{gray}\n{'='*50}{' 这是个 Python 用户自定义异常示例 ':~^38}{nocolor}")
try:
name = input(f"\n{'您的姓名:':>7}").strip()
if name == '梦幻精灵': # 条件达成 raise 殿堂。
raise MyException(f"{red}\n\n{name:^46}\n{' 这是我的名字!':~^44}\n{nocolor}")
else:
print(f"\n\n{blue}{'':~^50}\n{f' {name}, 很高兴认识您!':^38}\n{'':~^50}\n{nocolor}")
except MyException as error:
print(error)
finally: # 关键字 finally 之后的代码块,总是要招待的。
print(f"{gray}\n{' 这是个 Python 用户自定义异常示例 ':~^38}\n{'='*50}\n{nocolor}")
再列举一个触发自定义异常类型的实例——
print(f"{gray}\n{'='*50}{' 这是个 Python 用户自定义异常示例 ':~^38}{nocolor}")
try:
num = input(f"\n{'请输入1~100的数字:':8>}")
if not num.isdigit():
raise MyException(f"{red}\n{' 请数字!':~^46}\n{nocolor}")
elif int(num) < 1 or int(num) > 100:
raise MyException(f"{red}\n{' 您输入的数字超出范围!':~^39}\n{nocolor}")
else:
print(f"{green}\n{f' {num},输入正确。':~^44}\n{nocolor}")
except MyException as error:
print(error)
finally:
print(f"{gray}\n{' 这是个 Python 用户自定义异常示例 ':~^38}\n{'='*50}\n{nocolor}")
其实,也可以把超出范围的异常捕获分开——
elif int(num) < 1 or int(num) > 100:
raise MyException(f"{red}\n{' 您输入的数字超出范围!':~^39}\n{nocolor}")
elif int(num) < 1:
raise MyException(f"{red}\n{' 您输入的数字超出下限1!':~^39}\n{nocolor}")
elif int(num) > 100:
raise MyException(f"{red}\n{' 您输入的数字超出上限100!':~^39}\n{nocolor}")
#!/sur/bin/nve python
# coding: utf-8
class MyException(Exception):
def __init__(self, error_tip):
self.tip = error_tip
def __str__(self):
return self.tip
if __name__ == '__main__':
gray = '\033[2m' # 灰色。
blue = '\033[34;1m' # 亮蓝。
green = '\033[32m' # 绿色。
red = '\033[31m' # 红色。
nocolor = '\033[0m' # 还原 python 默认配色。
'''# raise one
print(f"{gray}\n{'='*50}{' 这是个 Python 用户自定义异常示例 ':~^38}{nocolor}")
try:
name = input(f"\n{'您的姓名:':>7}").strip()
if name == '梦幻精灵':
raise MyException(f"{red}\n\n{name:^46}\n{' 这是我的名字!':~^43}\n{nocolor}")
else:
print(f"\n\n{blue}{'':~^50}\n{f' {name}, 很高兴认识您!':^38}\n{'':~^50}\n{nocolor}")
except MyException as error:
print(error)
finally:
print(f"{gray}\n{' 这是个 Python 用户自定义异常示例 ':~^38}\n{'='*50}\n{nocolor}")'''
# raise two
print(f"{gray}\n{'='*50}{' 这是个 Python 用户自定义异常示例 ':~^38}{nocolor}")
try:
num = input(f"\n{'请输入1~100的数字:':8>}")
if not num.isdigit():
raise MyException(f"{red}\n{' 请输入数字!':~^44}\n{nocolor}")
elif int(num) < 1:
raise MyException(f"{red}\n{' 您输入的数字超出下限1!':~^39}\n{nocolor}")
elif int(num) > 100:
raise MyException(f"{red}\n{' 您输入的数字超出上限100!':~^39}\n{nocolor}")
else:
print(f"{green}\n{f' {num},输入正确。':~^44}\n{nocolor}")
except MyException as error:
print(error)
finally:
print(f"{gray}\n{' 这是个 Python 用户自定义异常示例 ':~^38}\n{'='*50}\n{nocolor}")
我的HOT博:
本次共计收集 214 篇博文笔记信息,总阅读量 34.60w,平均阅读量 1616。已生成 22 篇阅读量不小于 3000 的博文笔记索引链接。数据采集于 2023-05-28 05:47:47 完成,用时 4 分 31.83 秒。
精品文章:
来源:老齐教室
◆ Python 入门指南【Python 3.6.3】
好文力荐:
CSDN实用技巧博文: