1常见异常类
异常通过raise语句来触发,自定义异常形式为class SomeCustomException(Exception): pass
,此外可以自己重定义异常中的方法。
>>> 1/0
Traceback (most recent call last):
File "", line 1, in
ZeroDivisionError: division by zero
>>> raise Exception("Error Info")
Traceback (most recent call last):
File "", line 1, in
Exception: Error Info
>>>
2 捕获异常try....except
try:
x=int(input("input one int num:"))
y=int(input("input divider:"))
print("{}/{}={}".format(x,y,x/y))
except ZeroDivisionError:
print("y can't be zero")
3 异常的传播
3.1 except子句中使用raise来传递该异常
#ValueError("Value Error") from Exception("Exception Info")
try:
1/0
except ZeroDivisionError:
raise
E:\henry\Python\venv\Scripts\python.exe E:/henry/Python/Exception.py
Traceback (most recent call last):
File "E:/henry/Python/Exception.py", line 33, in
1/0
ZeroDivisionError: division by zero
Process finished with exit code 1
3.2 except子句中使用raise AnotherException来引起别的异常
try:
1/0
except ZeroDivisionError:
raise ValueError("Value Error")
E:\henry\Python\venv\Scripts\python.exe E:/henry/Python/Exception.py
Traceback (most recent call last):
File "E:/henry/Python/Exception.py", line 33, in
1/0
ZeroDivisionError: division by zero
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "E:/henry/Python/Exception.py", line 35, in
raise ValueError("Value Error")
ValueError: Value Error
3.3 raise …from …
使用raise … from None
来禁用异常上下文:
try:
1/0
except ZeroDivisionError:
raise ValueError("Value Error") from None
E:\henry\Python\venv\Scripts\python.exe E:/henry/Python/Exception.py
Traceback (most recent call last):
File "E:/henry/Python/Exception.py", line 35, in
raise ValueError("Value Error") from None
ValueError: Value Error
使用raise…from…
来自定义异常上下文:
try:
1/0
except ZeroDivisionError:
raise ValueError("Value Error") from Exception("Exception Info")
E:\henry\Python\venv\Scripts\python.exe E:/henry/Python/Exception.py
Exception: Exception Info
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "E:/henry/Python/Exception.py", line 35, in
raise ValueError("Value Error") from Exception("Exception Info")
ValueError: Value Error
3.4 多个except子句来处理异常
将字符串作为除数或被除数时会引发TypeError异常。
try:
x=input("input one int num:")
y=input("input divider:")
print("{}/{}={}".format(x,y,x/y))
except ZeroDivisionError:
print("y can't be zero")
except TypeError:
print("you should input one number ranther than one string")
3.5 使用(except1,except2,…)
来同时处理多个异常
try:
x=input("input one int num:")
y=input("input divider:")
print("{}/{}={}".format(x,y,x/y))
except (ZeroDivisionError,TypeError):
print("Error Input")
3.6 捕获对象
try:
x=input("input one int num:")
y=input("input divider:")
print("{}/{}={}".format(x,y,x/y))
except (ZeroDivisionError,TypeError) as e:
print(e)
3.7 try...except...else
在没有出现异常时执行一个else子句
while True:
try:
x=int(input("Enter the first num:"))
y=int(input("Enter the second num:"))
val=x/y
print("x/y is",val)
except Exception as e: #存在异常时会重新输入数字
print("Error Input:",e)
print("Try again!!!")
else: #没有异常时会进入此处执行
break
3.8 finally子句
无论是否存在异常,均会执行finally子句,finally子句中适合执行一些清理工作(如关闭套接字等)。
while True:
try:
x=int(input("Enter the first num:"))
y=int(input("Enter the second num:"))
val=x/y
print("x/y is",val)
except Exception as e: #存在异常时会重新输入数字
print("Error Input:",e)
print("Try again!!!")
else: #没有异常时会进入此处执行
break
finally: #无论是否存在异常,均会执行finallly子句
print("clean up")
4 警告
如果你只想发出警告,指出情况偏离了正轨,可使用模块warnings中的函数warn。
>>> from warnings import warn
>>> warn("I've got a bad feeling about this.")
__main__:1: UserWarning: I've got a bad feeling about this.
>>>
如果其他代码在使用你的模块,可使用模块warnings中的函数filterwarnings来抑制你发出的警告(或特定类型的警告),并指定要采取的措施,如"error"或"ignore"。
>>> from warnings import filterwarnings
>>> filterwarnings("ignore")
>>> warn("Anyone out there?")
>>> filterwarnings("error")
>>> warn("Something is very wrong!")
Traceback (most recent call last):
File "", line 1, in
UserWarning: Something is very wrong!
如你所见,引发的异常为UserWarning。发出警告时,可指定将引发的异常(即警告类别),但必须是Warning的子类。如果将警告转换为错误,将使用你指定的异常。另外,还可根据异常来过滤掉特定类型的警告。
>>> filterwarnings("error")
>>> warn("This function is really old...", DeprecationWarning)
Traceback (most recent call last):
File "", line 1, in
DeprecationWarning: This function is really old...
>>> filterwarnings("ignore", category=DeprecationWarning)
>>> warn("Another deprecation warning.", DeprecationWarning)
>>> warn("Something else.")
Traceback (most recent call last):
File "", line 1, in
UserWarning: Something else.