例外狀況

Python 物件導向程式設計入門

George Boorman

Curriculum Manager, DataCamp

a = 1
a / 0
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
    1/0
ZeroDivisionError: division by zero
a = [1,2,3]
a[5]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
    a[5]
IndexError: list index out of range
a = 1
a + "Hello"
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
    a + "Hello"
TypeError: unsupported operand type(s) for +: /
'int' and 'str'
a = 1
a + b
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
    a + b
NameError: name 'b' is not defined
Python 物件導向程式設計入門

例外處理

  • 當拋出例外時,避免程式終止
  • try - except - finally
try:
    print(5 + "a")

except TypeError: print("You can't add an integer to a string, but you can multiply them!")
# 可有多個 except 區塊 except AnotherExceptionHere: # 若發生 AnotherExceptionHere,執行此程式碼
# 選用的 finally 區塊 finally: print(5 * "a")
Python 物件導向程式設計入門

例外處理輸出

You can't add an integer to a string, but you can multiply them!
aaaaa
Python 物件導向程式設計入門

拋出例外

def make_list_of_ones(length):
    if length <= 0:
        # 發生 ValueError 時的自訂訊息
        # 將停止程式並拋出錯誤
       raise ValueError("Invalid length!")
    return [1]*length

make_list_of_ones(-1)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
    make_list_of_ones(-1)
  File "<stdin>", line 3, in make_list_of_ones
    raise ValueError("Invalid length!")
ValueError: Invalid length!
Python 物件導向程式設計入門

例外是類別

  • 例外從 BaseExceptionException 繼承
    BaseException
    +-- Exception
        +-- ArithmeticError                     
        |    +-- FloatingPointError
        |    +-- OverflowError
        |    +-- ZeroDivisionError              
        +-- TypeError
        +-- ValueError
        |    +-- UnicodeError
        |         +-- UnicodeDecodeError
        |         +-- UnicodeEncodeError
        |         +-- UnicodeTranslateError
        +-- RuntimeError
       ...
    +-- SystemExit
    ...
    
1 https://docs.python.org/3/library/exceptions.html
Python 物件導向程式設計入門

自訂例外

  • Exception 或其子類別繼承
  • 通常是空類別
class BalanceError(Exception): 
    pass

class Customer: def __init__(self, name, balance): if balance < 0 : raise BalanceError("Balance has to be non-negative!") else: self.name = name self.balance = balance
Python 物件導向程式設計入門

建構子中的例外

cust = Customer("Larry Torres", -100)
Traceback (most recent call last):
  File "script.py", line 11, in <module>
    cust = Customer("Larry Torres", -100)
  File "script.py", line 6, in __init__
    raise BalanceError("Balance has to be non-negative!")
BalanceError: Balance has to be non-negative!
Python 物件導向程式設計入門

例外會終止程式

  • 例外中斷了建構子 → 物件未建立
cust
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
    cust
NameError: name 'cust' is not defined
Python 物件導向程式設計入門

捕捉自訂例外

try:
    cust = Customer("Larry Torres", -100)
except BalanceError:
    cust = Customer("Larry Torres", 0)
Python 物件導向程式設計入門

一起來練習吧!

Python 物件導向程式設計入門

Preparing Video For Download...