Exceptions

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 เบื้องต้นสำหรับการเขียนโปรแกรมเชิงวัตถุ

การจัดการ Exception

  • ป้องกันไม่ให้โปรแกรมหยุดทำงานเมื่อเกิด exception ขึ้น
  • try - except - finally:
try:
    print(5 + "a")

except TypeError: print("You can't add an integer to a string, but you can multiply them!")
# Can have multiple except blocks except AnotherExceptionHere: # Run this code if AnotherExceptionHere happens
# Optional finally block finally: print(5 * "a")
Python เบื้องต้นสำหรับการเขียนโปรแกรมเชิงวัตถุ

ผลลัพธ์จากการจัดการ Exception

You can't add an integer to a string, but you can multiply them!
aaaaa
Python เบื้องต้นสำหรับการเขียนโปรแกรมเชิงวัตถุ

การ Raise Exception

def make_list_of_ones(length):
    if length <= 0:
        # Custom message if ValueError occurs
        # Will stop the program and raise the error
       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 เบื้องต้นสำหรับการเขียนโปรแกรมเชิงวัตถุ

Exception คือคลาส

  • Exception สืบทอดมาจาก BaseException หรือ Exception
    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 แบบกำหนดเอง

  • สืบทอดจาก 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 เบื้องต้นสำหรับการเขียนโปรแกรมเชิงวัตถุ

Exception ใน Constructor

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 เบื้องต้นสำหรับการเขียนโปรแกรมเชิงวัตถุ

Exception หยุดการทำงานของโปรแกรม

  • Exception ขัดขวาง constructor → ออบเจกต์จึงไม่ถูกสร้าง
cust
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
    cust
NameError: name 'cust' is not defined
Python เบื้องต้นสำหรับการเขียนโปรแกรมเชิงวัตถุ

การดัก Exception แบบกำหนดเอง

try:
    cust = Customer("Larry Torres", -100)
except BalanceError:
    cust = Customer("Larry Torres", 0)
Python เบื้องต้นสำหรับการเขียนโปรแกรมเชิงวัตถุ

มาฝึกกันเถอะ!

Python เบื้องต้นสำหรับการเขียนโปรแกรมเชิงวัตถุ

Preparing Video For Download...