İstisnalar

Python'da Nesne Yönelimli Programlama

Alex Yarosh

Content Quality Analyst @ 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'da Nesne Yönelimli Programlama

İstisna yönetimi

  • Bir istisna oluştuğunda programın sonlanmasını önler
  • try - except - finally:
try:
  # Bazı kodları çalıştırmayı dene

except ExceptionNameHere: # ExceptionNameHere olursa bu kodu çalıştır
except AnotherExceptionHere: #<-- birden fazla except bloğu # AnotherExceptionHere olursa bu kodu çalıştır ...
finally: #<-- isteğe bağlı # Ne olursa olsun bu kodu çalıştır
Python'da Nesne Yönelimli Programlama

İstisna fırlatma

  • raise ExceptionNameHere('Hata mesajı buraya')
def make_list_of_ones(length):
    if length <= 0:
       raise ValueError("Geçersiz uzunluk!")  # <--- Programı durdurur ve hata verir
    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("Geçersiz uzunluk!")
ValueError: Geçersiz uzunluk!
Python'da Nesne Yönelimli Programlama

İstisnalar sınıflardır

  • Standart istisnalar BaseException veya Exception sınıflarından türetilir
    BaseException
    +-- Exception
        +-- ArithmeticError                     # <--- 
        |    +-- FloatingPointError
        |    +-- OverflowError
        |    +-- ZeroDivisionError              # <---
        +-- TypeError
        +-- ValueError
        |    +-- UnicodeError
        |         +-- UnicodeDecodeError
        |         +-- UnicodeEncodeError
        |         +-- UnicodeTranslateError
        +-- RuntimeError
       ...
    +-- SystemExit
    ...
    
1 https://docs.python.org/3/library/exceptions.html
Python'da Nesne Yönelimli Programlama

Özel istisnalar

  • Exception veya alt sınıflarından birinden türetilir
  • Genellikle boş bir sınıftır
class BalanceError(Exception): pass
class Customer:
   def __init__(self, name, balance):
    if balance < 0 :
       raise BalanceError("Bakiye negatif olamaz!")
    else:
       self.name, self.balance = name, balance

Python'da Nesne Yönelimli Programlama
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("Bakiye negatif olamaz!")
BalanceError: Bakiye negatif olamaz!
  • İstisna yapıcıyı durdurdu → nesne oluşturulmadı
cust
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
    cust
NameError: name 'cust' is not defined
Python'da Nesne Yönelimli Programlama

Özel istisnaları yakalama

try:
  cust = Customer("Larry Torres", -100)
except BalanceError:
  cust = Customer("Larry Torres", 0)
Python'da Nesne Yönelimli Programlama

Hadi pratik yapalım!

Python'da Nesne Yönelimli Programlama

Preparing Video For Download...