1. 程式人生 > 實用技巧 >學習心得2020.08.30

學習心得2020.08.30

032異常處理

file_name=input('請輸入需要開啟的檔名:')
f=open(file_name)
print('檔案的內容是:')
for each_line in f:
    print(each_line)

>>> my_list=['小甲魚是帥哥']
>>> assert len(my_list)>0
>>> my_list.pop()
'小甲魚是帥哥'
>>> assert len(my_list)>0
Traceback (most recent call last):
  File "<pyshell#3>", line 1, in <module>
    assert len(my_list)>0
AssertionError
>>> my_list.fishc
Traceback (most recent call last):
  File "<pyshell#4>", line 1, in <module>
    my_list.fishc
AttributeError: 'list' object has no attribute 'fishc'
>>> my_list=[1,2,3]
>>> my_lsit[3]
Traceback (most recent call last):
  File "<pyshell#6>", line 1, in <module>
    my_lsit[3]
NameError: name 'my_lsit' is not defined
>>> my_list[2]
3
>>> my_dict={'one':1,'two':2,'three':3}
>>> my_dict['one']
1
>>> my_dict['two']
2
>>> my_dict['four']
Traceback (most recent call last):
  File "<pyshell#11>", line 1, in <module>
    my_dict['four']
KeyError: 'four'
>>> 1+'1'
Traceback (most recent call last):
  File "<pyshell#12>", line 1, in <module>
    1+'1'
TypeError: unsupported operand type(s) for +: 'int' and 'str'

033異常檢測

  • try-except語句
    try:
    檢測範圍
    except Exception[as reason]:
    出現異常(Exception)後的處理程式碼
try:
    sum=1+'1'
    f=open('我為什麼是一個檔案.txt')
    print(f.read())
    f.close()
except OSError as reason:
    print('檔案出錯啦,出錯的原因是:'+str(reason))
except TypeError as reason:
    print('型別出錯啦,出錯的原因是:'+str(reason))
  • try-finally語句
    try:
    檢測範圍
    except Exception[as reason]:
    出現異常(Exception)後的處理程式碼
    finally:
    無論如何都會被執行的程式碼
try:
    f=open('我為什麼是一個檔案.txt','w')
    print(f.write('我存在了!'))
    sum=1+'1'
except (OSError,TypeError):
    print('檔案出錯啦')
finally:
    f.close()
  • raise語句
    可以在其中新增解釋異常原因的語句
>>> raise ZeroDivisionError('除數為零的異常')
Traceback (most recent call last):
  File "<pyshell#13>", line 1, in <module>
    raise ZeroDivisionError('除數為零的異常')
ZeroDivisionError: 除數為零的異常