python - intermediate - 9 - error handling



Hata ayıklama


python`dan exception kisminda hatalarin cesitleri bulunabilir

Zero division error

try:
    x=int(input('x: '))
    y=int(input('y: '))
    print(x/y)

except ZeroDivisionError:
    print('y icin 0 girilemez')

#
x: 10 y: 0 y icin 0 girilemez

Value error

try:
    x=int(input('x: '))
    y=int(input('y: '))
    print(x/y)

except ZeroDivisionError:
    print('y icin 0 girilemez')
except ValueError
    print('x ve y icin sayisal deger girilmelidir')

#
x: 10 y: 2m x ve y icin sayisal deger girilmelidir

Hepsine ayni hata mesaji:

try:
    x=int(input('x: '))
    y=int(input('y: '))
    print(x/y)

except (ZeroDivisionError,ValueError):
    print('yanlis bilgi girdiniz')

#
x: h yanlis bilgi girdiniz

Hepsine ayni msj + hata bilgisini yazilmasi

try:
    x=int(input('x: '))
    y=int(input('y: '))
    print(x/y)

except (ZeroDivisionError,ValueError) as errX:
    print('yanlis bilgi girdiniz')
    print(errX)

#
x: 9 y: d33 yanlis bilgi girdiniz invalid literal for int() with base 10: 'd33'

Baska yontem ile hata mesaji yazimi ve While dongusu

while True:
    try:
        x=int(input('x: '))
        y=int(input('y: '))
        print(x/y)

    # except (ZeroDivisionError,ValueError) as errX:
    except Exception as ex:
        print('yanlis bilgi girdiniz', ex)

    else:
        break

#
x: 2 y: a yanlis bilgi girdiniz invalid literal for int() with base 10: 'a' x: 3 y: 2 1.5

Finally: hep calisan blok

while True:
    try:
        x=int(input('x: '))
        y=int(input('y: '))
        print(x/y)

    # except (ZeroDivisionError,ValueError) as errX:
    except Exception as ex:
        print('yanlis bilgi girdiniz', ex)

    else:
        break
    finally: # her ne olursa olsun calisir # dosya kapatir
        print('try except sonlandi')
#
x: 5 y: 2 2.5 try except sonlandi

#
x: 2
y: w
yanlis bilgi girdiniz invalid literal for int() with 
base 10: 'w'
try except sonlandi
x:

Kendi kistaslarimiz ile hata mesaji yaratmak - raising an exception

x =10
if x>5:
    raise Exception("x 5 den buyuk olamaz")

#
Exception: x 5 den buyuk olamaz

- ornek 2 -
def check_password(psw):
    import re
    if len(psw)<8:
        raise Exception ("parola en az 7 karakterli olmali")
    elif not re.search("[0-9]",psw):
        raise Exception ("rakam icermeli")
    elif not re.search("[a-z]",psw):
        raise Exception ("kucuk harf icermeli")
    elif not re.search("[A-Z]",psw):
        raise Exception ("buyuk harf icermeli")
    elif not re.search("[_@$#]",psw):
        raise Exception ("parola _@$# bir tanesini icermeli")    
    elif re.search("\s",psw):
        raise Exception ("parola bosluk yani space iceremez")
password ="123457Aa"

try:
    check_password(password)
except Exception as ex:
    print(ex)
#
parola _@$# bir tanesini icermeli





Comments

Popular posts from this blog

python - pro - 20 - SQLite

python - pro - 21 - NoSQL

python-beginner - 1 - strings splits