Python – raise exception

Loading

測試環境為 CentOS 8 x86_64 (虛擬機)

如果要在發生錯誤時直接中斷掉程式,可以使用 raise 來發起例外 (exception) 這樣程式就會中斷執行並在命令列上列印出相對應的錯誤訊息.

raise 後面接著 異常類名稱 (描述信息),其 異常類名稱 請參考官方網站說明 : https://docs.python.org/3/library/exceptions.html

raise [exceptionName [(reason)]]

參考文章 – https://openhome.cc/zh-tw/python/exception/raise/

範例:

[root@localhost ~]# vi raise1.py 
class Account:
    def __init__(self, balance):
        self.balance = balance

    def check_balance(self):
        if self.balance <= 0:
            raise ValueError('Not a Positive real numbers and your balance: ' + str(self.balance))
        else:
            print('Your balance is: ' + str(self.balance))

acct1 = Account(100) 
acct1.check_balance()

acct2 = Account(-100) 
acct2.check_balance()

執行結果

[root@localhost ~]# python3 raise1.py 
Your balance is: 100
Traceback (most recent call last):
  File "raise1.py", line 15, in <module>
    acct2.check_balance()
  File "raise1.py", line 7, in check_balance
    raise ValueError('Not a Positive real numbers and your balance: ' + str(self.balance))
ValueError: Not a Positive real numbers and your balance: -100

說明:
當存款 balance 為正值時,會執行 else.

acct1 = Account(100) 
acct1.check_balance()

執行結果

Your balance is: 100

當 balance 為負值,所以 Raise exception.

acct2 = Account(-100) 
acct2.check_balance()

執行結果

Traceback (most recent call last):
  File "raise1.py", line 15, in <module>
    acct2.check_balance()
  File "raise1.py", line 7, in check_balance
    raise ValueError('Not a Positive real numbers and your balance: ' + str(self.balance))
ValueError: Not a Positive real numbers and your balance: -100

其中 ValueError 為
Raised when an operation or function receives an argument that has the right type but an inappropriate value, and the situation is not described by a more precise exception such as IndexError.

通常會搭配 Try-except statement – https://benjr.tw/104252 來使用.

[root@localhost ~]# vi raise2.py 
class Account:
    def __init__(self, balance):
        self.balance = balance

    def check_balance(self):
        try:
            if self.balance <= 0:
                raise ValueError('Not a Positive real numbers and your balance: ' + str(self.balance))

        except ValueError as e:
            print("引發異常:",repr(e))

        else:
            print('Your balance is: ' + str(self.balance))

acct2 = Account(-100) 
acct2.check_balance()

須注意:以上程式是使用 Try , expect 與 else 的語法,非前面 if else 語法.

執行結果

[root@localhost ~]# python3 raise2.py 
引發異常: ValueError('Not a Positive real numbers and your balance: -100',)
沒有解決問題,試試搜尋本站其他內容

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *

這個網站採用 Akismet 服務減少垃圾留言。進一步了解 Akismet 如何處理網站訪客的留言資料