python總結(十三) 錯誤與除錯

2021-09-24 18:40:34 字數 4291 閱讀 6184

1、處理錯誤:

try:

print('try...')

r = 10 / int('2')

print('result:', r)

except exception as e:

print('valueerror:', e)

except zerodivisionerror as e:

print('zerodivisionerror:', e)

else:

"""當沒有錯誤發生時,會自動執行else語句:"""

print('no error!')

finally:

print('finally...')

print('end')

2、丟擲錯誤:

try:

10 / 0

except zerodivisionerror:

raise valueerror('input error!')

3、自定義丟擲錯誤:

# err_raise.py

class fooerror(valueerror):

pass

def foo(s):

n = int(s)

if n==0:

raise fooerror('invalid value: %s' % s)

return 10 / n

foo('0')

1、很low的程式設計師除錯程式用print

def foo(s):

n = int(s)

print('>>> n = %d' % n)

return 10 / n

def main():

foo('0')

main()

2.處處print不太好,用斷言:斷言正確,不會輸出任何東西。斷言錯誤,則會丟擲異常:

def foo(s):

n = int(s)

assert n != 0, 'n is zero!'

return 10 / n

def main():

foo('0')

"""斷言錯誤的輸出"""

"""traceback (most recent call last):

file "c:/users/lenovo/pycharmprojects/matplot_graph/venv/classtext.py", line 7, in main()

file "c:/users/lenovo/pycharmprojects/matplot_graph/venv/classtext.py", line 6, in main

foo('0')

file "c:/users/lenovo/pycharmprojects/matplot_graph/venv/classtext.py", line 3, in foo

assert n != 0, 'n is zero!'

assertionerror: n is zero!

"""

程式中如果到處充斥著assert,和print()相比也好不到哪去.啟動python直譯器時可以用-o(大寫字母)引數來關閉assert。

$ python -o err.py

traceback (most recent call last):

...zerodivisionerror: division by zero

3、pdb單步除錯:

(1)啟動:

python -m pdb err.py
(2)輸入命令l來檢視**

(3)輸入命令n可以單步執行**

(4)任何時候都可以輸入命令p 變數名來檢視變數

(5)輸入命令q結束除錯,退出程式 

(6) c 繼續執行

4.第二種:**中加

import pdb

pdb.set_trace()

1.**

import unittest

from dict import dict

class testdict(unittest.testcase):

def test_init(self):

d = dict(a=1, b='test')

"""測試的類名"""

self.assertequal(d.a, 1)

self.assertequal(d.b, 'test')

self.asserttrue(isinstance(d, dict))

def test_key(self):

d = dict()

d['key'] = 'value'

self.assertequal(d.key, 'value')

def test_attr(self):

d = dict()

d.key = 'value'

self.asserttrue('key' in d)

self.assertequal(d['key'], 'value')

def test_keyerror(self):

d = dict()

with self.assertraises(keyerror):

value = d['empty']

def test_attrerror(self):

d = dict()

with self.assertraises(attributeerror):

value = d.empty

def setup(self):

print('setup...')

def teardown(self):

print('teardown...')

2、執行測試

python -m unittest mydict_test
當然,引數是可變的:

python -m unittest mydict_test mytest
可以執行無限多個測試類

1.測試注釋中的的**:

class dict(dict):

'''****** dict but also support access as x.y style.

>>> d1 = dict()

>>> d1['x'] = 100

>>> d1.x

100>>> d1.y = 200

>>> d1['y']

200>>> d2 = dict(a=1, b=2, c='3')

>>> d2.c

'3'>>> d2['empty']

traceback (most recent call last):

...keyerror: 'empty'

>>> d2.empty

traceback (most recent call last):

...attributeerror: 'dict' object has no attribute 'empty'

'''def __init__(self, **kw):

super(dict, self).__init__(**kw)

def __getattr__(self, key):

try:

return self[key]

except keyerror:

raise attributeerror(r"'dict' object has no attribute '%s'" % key)

def __setattr__(self, key, value):

self[key] = value

if __name__=='__main__':

import doctest

doctest.testmod()

2.必須在終端執行:

python mydice2.py

Python錯誤與除錯

try catch語法 try pass except someerror as e pass except someerror as e pass finally pass日誌級別 critical error warning info debug notset import logging lo...

JavaScript 錯誤與除錯

首先先說錯誤的概念預處理 電腦程式的錯誤分為兩種 語法錯誤和邏輯錯誤。比如alert拼寫錯誤,寫成了alter vara 3 4 alert a alter 7 a alert a 執行結果只顯示了7 後面的結果沒有顯示,說明後面的 沒有執行。因為輸出7後遇到了語法錯誤,程式終止執行。上例也進一步說...

python錯誤 除錯和測試

錯誤 除錯和測試 當我們認為某些 可能會出錯時,就可以用try來執行這段 如果執行出錯,則後續 不會繼續執行,而是直接跳轉至錯誤處理 即except語句塊,執行完except後,如果有finally語句塊,則執行finally語句塊,至此,執行完畢。出錯的時候,一定要分析錯誤的呼叫棧資訊,才能定位錯...