1. 程式人生 > 其它 >Control of Mobile Robots 學習筆記(二、三)Mobile robot, Linear system

Control of Mobile Robots 學習筆記(二、三)Mobile robot, Linear system

1.1 異常處理

有時可將程式錯誤(Error)稱作程式異常(Exception)。

  • 出現錯誤程式終止。
  • 出現異常程式終止,也可以捕捉異常和撰寫異常處理程式,處理完程式可以繼續執行。

1.1.1 除數為0的異常

>>> 3 / 0
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ZeroDivisionError: division by zero

程式終止,打印出現異常的資訊(除0錯誤)

1.1.2 異常處理程式

try:
    指令 # 可能發出異常
except [異常型別]:
    異常處理程式

執行過程:

  • try程式碼塊:指令可能會丟擲異常
  • except程式碼塊:每個try可以跟多個except程式碼塊,用於處理所有可能丟擲的異常。異常如果省略了型別,則會捕捉所有的異常,如果指定異常型別,則會捕捉該型別異常及子類異常。
def division(x,y):
    try:
        return x / y
    except ZeroDivisionError:
        print("除數不能為零")
    except TypeError as e:  # 異常物件
        print(e)

division(3,0)  # 除數不能為零
division("a","b")  # unsupported operand type(s) for /: 'str' and 'str'\

except 後面可以寫成as 異常物件名的方式,之後處理時可輸出異常物件的資訊。

1.1.3 try - except - else

try:
    ...
except 異常物件:
    ...
else:
    沒有發生異常時執行這個程式碼塊。
filename = "d:/2txt"
try:
    with open(filename) as fp:
        data = fp.read()
except FileNotFoundError:
    print("未找到檔案:{}".format(filename))
else:
    print(data)

如果找到檔案了,讀取資料並顯示,未找到列印未找到。

1.2 常見的異常物件

異常型別 說明
AttributeError 物件沒有這個屬性(
Exception 通用異常父類,它的父類是BaseException
FileNotFoundError 打不到檔案
IOError 在輸入輸出時發生錯誤
IndexError 下標越界
KeyError 在對映中沒有這個鍵
MemoryError 請求記憶體出錯
NameError 物件名稱未宣告
SyntaxError 語法錯誤
SystemError 系統錯誤
TypeError 資料型別錯誤
ValueError 傳入無效引數
ZeroDivisionError 除數為0

1.3 多重捕獲

try:
    ...
except 異常物件1:
	...
except 異常物件2:
    ...
    

except可以是多個。注意:如果有父子關係的異常,要子類異常在前,父類異常在後,否則子類異常永遠不會捕獲到異常。

多重捕獲多個異常的另一種方法:

try:
    ...
except(異常型別1, 異常型別2, ...):
    ...

如:

def f(a, b):
    try:
        return a / b
    except(ZeroDivisionError, TypeError) as e:
        print(e)


f(3, 0)
f(3, "a")

1.4 捕獲所有異常

try:
    ...
except:
    ...

except後面沒有跟任意型別。

1.5 丟擲自定義的異常

raise Exception("異常資訊")
class LoginError(Exception):
    def __init__(self, message):
        super().__init__(message)


def login(username, password):
    if username == 'admin' and password == 'admin':
        return True
    else:
        raise LoginError("使用者名稱或密碼錯誤")  # 丟擲異常資訊


try:
    login("admin","admin")
except LoginError as e:
    print(e)
else:
    print("登入成功")

1.6 異常堆疊跟蹤資訊

出現錯誤時會顯示堆疊資訊,定位錯誤檔案及原因,可以把這個資訊寫入檔案中。

traceback.format_exc() # 打印出錯資訊
try:
    raise Exception("出錯啦!")
except Exception as e:
    print(e) # 出錯啦!
    
# 列印:出錯啦!


import traceback

try:
    raise Exception("出錯啦!")
except Exception as e:
    traceback.print_exc() # 列印堆疊資訊
    
'''
Traceback (most recent call last):
  File "D:\develop\school\main.py", line 4, in <module>
    raise Exception("出錯啦!")
Exception: 出錯啦!
'''   



可以把這個資訊寫入檔案 , 用traceback.format_exc() 返回資訊

import traceback

try:
    raise Exception("出錯啦!")
except Exception as e:
    with open("d:/err.txt", "a") as f:
        f.write(traceback.format_exc())

1.7 資源釋放

try:
    ...
except [異常型別n]:
    ...
finally:
    ...

finally必須放在最後,無論是否發生異常都會執行。

對於有些程式設計需要手動釋放資源的,可以放在這裡。

1.8 自定義異常類

class 異常類名(Exception):
    def __init__(self, message):
        super().__init__(message)

1.9 斷言

斷言用於程式的除錯,使用的很少。

assert 表示式 , '斷言資訊'

如果表達的值為False,則丟擲斷言資訊,相當於 raise AssertionError('error')

a = 0
assert a > 0, "a不能小於0"

'''
Traceback (most recent call last):
  File "D:\develop\school\main.py", line 2, in <module>
    assert a > 0, "a不能小於0"
AssertionError: a不能小於0
'''