Python基礎 異常

2021-07-10 14:52:44 字數 1412 閱讀 4676

google c++ style中禁止使用異常。

python中也有異常,就簡單分享一下。

1/0就會產生異常。

按自己的方式出錯

raise語句

>>>raise exception

traceback (most recent all last):

自定義異常類

class

somecustomexception

(exception):

pass

捕捉異常 try/except

x = input('enter the

first

number: ')

y = input('enter the

second

number: ')

print x/y

except zerodivisonerror:

print 'the second

number can't be zero!'

多個except

x = input('enter the

first

number: ')

y = input('enter the

second

number: ')

print x/y

except zerodivisonerror:

print 'the second

number can't be zero!'

except typeerror:

print 'that wasn't a number, was it?'

乙個excep捕捉多個異常

try:

x = input('enter the first number: ')

y = input('enter the second number: ')

print x/y

except (zerodivisonerror, typeerror, nameerror):

print

'your numbers were bogus...'

try/except/else

try:

print

' 'except:

print

' 'else:

print

' '

finally語句

不管是否引發了異常,finall語句都會執行。

python異常基礎

try後面至少要有一項,亦可以選擇 except else finally中的任意組合 assert語句一般用於開發時對程式條件的驗證,只有當內建 debug 為true時,assert語句才有效。當python指令碼以 o選項編譯成為位元組碼檔案時,assert 語句將被移除。except 帶引數...

python基礎 異常

處理異常的目的是保證程式在出現錯誤的時候,可以繼續執行下去,而不會立即終止 語法 try 塊 可能會出錯的語句 except 異常型別 as異常名 塊 出現錯誤的處理方式 except 異常型別 as 異常名 塊 出現錯誤的處理方式 else 塊 沒有錯誤時執行的語句 finally 塊 是否有異常...

Python基礎 異常

python中遇到錯誤後,會引發異常。python中使用異常物件來表示異常情況。如果異常物件未被處理或者捕捉,程式就會用所謂的回溯 traceback 來終止執行。下面是乙個例子 def func1 raise exception if name main func1 執行之後報錯 venv e c...