異常就是語法正常的前提下,程式執行時報錯就是異常
當python指令碼發生異常時我們需要捕獲處理它,否則程式會終止執行
print('hello world')
print(1/0) #
zerodivisionerror: division by zero
print('
**結束
')
異常處理 try,except,else,finally,raise程式從上到下執行,先執行try的**,如果**報錯,則不會執行下面的**
執行except中的異常**
如果try沒報錯,則不執行except中**
try:
print('
hello word')
print(1/0)
except
indexerror:
print('
索引異常')
except
zerodivisionerror:
print('
o是除數異常')
except
:
print("
**有錯誤")
print('
最後的**
')
常見的報錯資訊:
zerodivisionerror,indexerror,nameerror,filenotfounderror,fileexistserror,typeerrortry正常執行結束,不會走except,走else
try中有錯誤,走except,不走else
無論**有無異常,都會走finally
try內層try無法捕獲異常,會向外傳遞:
print("
abc"
)
print(1/0)
print('b'
)except
baseexception:
print("
出現錯誤了")
else
:
print("
沒有異常")
finally
:
print("
有無異常都得給我跑起來
")
外層異常無法捕獲,會繼續向外傳遞,知道捕獲異常為止,沒捕獲報錯
try: with open(
'test2.py
','w+
') as f:
content =f.read()
try:
with open(
'test3.txt
','r
') as f:
(f.read())
except
fileexistserror:
print("
檔案未發現錯誤")
except
baseexception:
print('
外層捕獲
')
變數名也可以作為異常的物件,一般使用e來表示
e物件中包含了異常資訊的一些描述,我們可以根據描述做不同的處理
try:
print("
hello world")
print(1/0)
print("
over")
except
exception as e:
(e)def
func1():
print("
--func1-1-")
(num)
print('
---func1-2-')
deffunc2():
try:
print('
---func2--1')
func1()
print('
----func2--2')
except
filenotfounderror:
print("
func1出現異常")
else
:
print('
----func2--3')
finally
:
print("
最後的**")
try:
func2()
print('
func2執行完了')
except
nameerror:
print("
命名錯誤
")
使用者可以根據業務邏輯手動丟擲異常
並且使用者可以根據需求來丟擲系統異常(python 已經定義好的異常)和使用者自定義異常
try: name =a
ifname.isalpha():
raise exception('
不能全是字母')
except
baseexception as e:
print("
----exception----
",e)
class
shortinputexception(exception):
pass
try:
raise shortinputexception('
輸入太短')
except
baseexception as e:
(e)#
判斷輸入的字串長度,如果小於指定長度就報錯
class
myexception(exception):
def__init__
(self,length,atleast):
self.length = length #
輸入的字串長度
self.atleast =atleast
def__str__
(self):
return
'長度{},規定長度{}
'.format(self.length,self.atleast)
try:
msg = input("
請輸入:")
if len(msg)<5:
raise myexception(len(msg),5)
except
exception as e:
print(e)
Python3 x基礎學習 property
1 property 內建裝飾器函式,把乙個方法呼叫方式變成屬性呼叫方式。將乙個方法當成乙個屬性使用 注意 property裝飾器只能在物件導向中使用 2 訪問使用 property 裝飾器裝飾函式可以直接呼叫函式名 會執行一段功能 函式 然後返回值 3.property裝飾器只能修飾不帶引數的方法...
Python3 x基礎學習 裝飾器
1.裝飾器函式的本質 乙個閉包函式 2.裝飾器函式的作用 在不修改原函式及其呼叫方式的情況下對原函功能進行擴充套件 3.語法格式 裝飾器名稱 def foo print foo foo 公司有n個部門,每個部門負責相應的業務 deff1 print 身份驗證 print f1 def f2 prin...
Python3 x基礎學習 os模組學習
使用os 模組對檔案進行一些相關操作 importos 1.重新命名檔案 os.rename 舊檔名,新檔名 os.rename test.txt test3.txt os.rename test4.txt test 2.刪除檔案 os.remove 檔名 os.remove test1.py 3....