異常的繼承
基類:Exception
先處理子類異常
class B(Exception):
pass
class C(B):
pass
class D(C):
pass
for cls in [D,C,B]:
try:
raise cls()
except D: #先處理子類異常
print("D")
except C:
print("C")
except B:
print("B")
輸出:
D
C
B
一次處理多個異常
except (RuntimeError, TypeError, NameError):
pass
引發異常
raise NameError("hello")
輸出:
Traceback (most recent call last):
File “11.py”, line 68, in
raise NameError(“hello”)
NameError: hello
raise NameError
Traceback (most recent call last):
File “11.py”, line 69, in
raise NameError
NameError
不處理異常,重新引發異常
try:
raise NameError("hello")
except NameError:
print("An exception occured")
raise
輸出:
An exception occured
Traceback (most recent call last):
File “11.py”, line 71, in
raise NameError(“hello”)
NameError: hello
自定義異常
直接或間接繼承Exception類
finally
try:
raise NameError
finally: #有無異常,必定執行
print('Goodbye')
完整示例
def divide(x, y):
try:
result = x / y
except ZeroDivisionError:
print("division by zero!")
else: #無異常執行
print("result is", result)
finally: #有無異常,必定執行;定義 Clean-up
print("executing finally clause")
# divide(2,1)
# divide(2,0)
# divide("hi",1)
divide(2,1)
輸出:
result is 2.0
executing finally clause
divide(2,0)
輸出:
division by zero!
executing finally clause
divide(“hi”,1)
輸出:
executing finally clause
Traceback (most recent call last):
File “11.py”, line 91, in
divide(“hi”,1)
File “11.py”, line 80, in divide
result = x / y
TypeError: unsupported operand type(s) for /: ‘str’ and ‘int’
其他實例
try:
f = open('myfile.txt')
s = f.readline()
i = int(s.strip())
except OSError as err: #文件不存在,捕捉此異常
print(sys.exc_info())
print(err)
print("OS error: {0}".format(err))
except ValueError:
print("Could not convert data to an integer.")
except:
print("Unexpected error:", sys.exc_info()[0]) #打印異常類,如:<class 'FileNotFoundError'>
raise
輸出:
(<class ‘FileNotFoundError’>, FileNotFoundError(2, ‘No such file or directory’), <traceback object at 0x000001EAD831D588>)
[Errno 2] No such file or directory: ‘myfile.txt’
OS error: [Errno 2] No such file or directory: ‘myfile.txt’
for arg in sys.argv[1:]:
try:
f = open(arg, 'r')
except OSError:
print('cannot open', arg)
else: #放在else語句,防止非代碼錯誤被隱藏
print(arg, 'has', len(f.readlines()), 'lines')
f.close()
try:
raise Exception('spam', 'eggs')
except Exception as inst:
print(type(inst)) # the exception instance
print(inst.args) # arguments stored in .args
print(inst) # __str__ allows args to be printed directly,
# but may be overridden in exception subclasses
x, y = inst.args # unpack args
print('x =', x)
print('y =', y)
輸出:
<class ‘Exception’>
(‘spam’, ‘eggs’)
(‘spam’, ‘eggs’)
x = spam
y = eggs