Hatalari Yakalayalim Beyler …

Iste , hata mesajimiz bu ve ciktinin onemli yeride “ValueError“. Asagidaki cikti yas soruldugunda string girildiginde alindi.

/Library/Frameworks/Python.framework/Versions/2.7/bin/python2.7 /Users/vahricmuhtaryan/PycharmProjects/fonksiyonlar1/test1.py
Yasin Kacdfdf
Traceback (most recent call last):
File “/Users/vahricmuhtaryan/PycharmProjects/fonksiyonlar1/test1.py”, line 5, in <module>
a = int(raw_input(“Yasin Kac”))
ValueError: invalid literal for int() with base 10: ‘dfdf’

Process finished with exit code 1

Baska bir ornek , buradada onemli olan “urllib3.exceptions.MaxRetryError” . Aciklamasi normal boye bir site yok baglanilacak.

/Library/Frameworks/Python.framework/Versions/2.7/bin/python2.7 /Users/vahricmuhtaryan/PycharmProjects/fonksiyonlar1/test1.py
Traceback (most recent call last):
File “/Users/vahricmuhtaryan/PycharmProjects/fonksiyonlar1/test1.py”, line 14, in <module>
istek = http_w_pool.request(‘get’,’http://www.yupyu42342342p.com&#8217;)
File “/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/urllib3/request.py”, line 69, in request
**urlopen_kw)
File “/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/urllib3/request.py”, line 90, in request_encode_url
return self.urlopen(method, url, **extra_kw)
File “/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/urllib3/poolmanager.py”, line 165, in urlopen
response = conn.urlopen(method, u.request_uri, **kw)
File “/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/urllib3/connectionpool.py”, line 628, in urlopen
release_conn=release_conn, **response_kw)
File “/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/urllib3/connectionpool.py”, line 628, in urlopen
release_conn=release_conn, **response_kw)
File “/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/urllib3/connectionpool.py”, line 628, in urlopen
release_conn=release_conn, **response_kw)
File “/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/urllib3/connectionpool.py”, line 608, in urlopen
_stacktrace=sys.exc_info()[2])
File “/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/urllib3/util/retry.py”, line 273, in increment
raise MaxRetryError(_pool, url, error or ResponseError(cause))
urllib3.exceptions.MaxRetryError: HTTPConnectionPool(host=’www.yupyu42342342p.com’, port=80): Max retries exceeded with url: / (Caused by NewConnectionError(‘<urllib3.connection.HTTPConnection object at 0x101def590>: Failed to establish a new connection: [Errno 8] nodename nor servname provided, or not known’,))

Process finished with exit code 1

Burada program hataya dusmeden bir uyari yaratmamiz gerekiyor , aslinda try icin gerekli kismi yaptik ve ValueError/urllib3.exceptions.MaxRetryError denen hatalari yakaladik onun icin kodu soyle duzenleyip bir sonraki adima gecebiliriz.
Asagida gordugunuz gibi calisacak kodu <try> kismi altina aldik ve daha once calisip hata aldigimizdan biliyoruzki “ValueError” hatasi almistik , bunu bekledigimizi belirtiyoruz except’de ve bu hatayi yakaladigimizda ne yapacagimizi soyluyoruz programa

try:
    #istek = http_w_pool.request('get','http://www.yupyu42342342p.com')
    a = int(raw_input("Yasin Kac"))
    print a

except ValueError:
    print "Sanirim harf girdiniz :("

Yukardaki koda eklenti yapalim , hem url hemde sayi yerine karakter hatasini yakalamak istiyoruz, gordugunuz gibi except sayisi artmaya basladi.

# -*- coding: utf-8 -*-
import urllib3


http_w_pool = urllib3.PoolManager()

try:
    istek = http_w_pool.request('get','http://www.yupyu42342342p.com')
    a = int(raw_input("Yasin Kac"))
    print a

except ValueError:
    print "Sanirim harf girdiniz :("

except urllib3.exceptions.MaxRetryError:
    print "ÜRL de birsey var ..." # ÜRL e takilmayin hatali yazdim sonra coding ekledim en ust satira

Mesela dogru hata beklentisi yazmadiginizda ne oluyor yani except urllib3.exceptions.MaxRetryError yerine sadece except MaxRetryError yazdigimizda ?

/Library/Frameworks/Python.framework/Versions/2.7/bin/python2.7 /Users/vahricmuhtaryan/PycharmProjects/fonksiyonlar1/test1.py
Traceback (most recent call last):
File “/Users/vahricmuhtaryan/PycharmProjects/fonksiyonlar1/test1.py”, line 16, in <module>
except MaxRetryError:
NameError: name ‘MaxRetryError’ is not defined

Process finished with exit code 1

Eger anlamsiz ama her iki hata icinde ayni mesaji vermek isteseydik bu durumda

except (ValueError,urllib3.exceptions.MaxRetryError):
    print "Äyni"

Diyelim herhangi bir exception yakalanamiyor ise hersey tamamdir diye dusunelim ve “else” kismini ekleyelim.

try:
    istek = http_w_pool.request('get','http://www.yupyup.com')
    a = int(raw_input("Yasin Kac"))
    print a

except (ValueError,urllib3.exceptions.MaxRetryError):
    print "Äyni"

else:
    print "Hersey yolunda"

Diyelim kod exception yakalasada yakalamasada bisiyler yapmak istiyoruz, buyrun yapin. Finally arastirdiginizda Cleanup olarak geciyor hani dosya actiysaniz kapatin , tcp baglanti actiysaniz kapatin gibi.

try:
    istek = http_w_pool.request('get','http://www.yupyup.com')
    a = int(raw_input("Yasin Kac"))
    print a

except (ValueError,urllib3.exceptions.MaxRetryError):
    print "Äyni"

else:
    print "Hersey yolunda"

finally:
    print "Hata versede olur vermesede ! Pasa gonlum iyi olsunda "

Istersek Argument kullanarak hatanin aciklamasinida alip kullanabiliriz

try:
  #  istek = http_w_pool.request('get','http://www.yupyup.com')
    a = int(raw_input("Yasin Kac"))
    print a


except ValueError, Argument:
    print "Sanirim harf girdiniz :(" , Argument

Aynisini soylede yazabiliriz

except ValueError as hataciktisi:
    print "Sanirim harf girdiniz :(" , hataciktisi

Su ana kadar hep belli bir hatayi yakalmaya calistik, bir suru hata olabilir o zaman catch-all gibi birsey lazim bunu icinde asagidaki gibi bir ornek isimizi gorebilir. Bunu icin sys modulune ihtiyacimiz var ve exc_info bize exeception hakkinda bilgi dondurecek. [0] yerine 1 veya 2 koyarak deneyin farkli ciktilar alacaksiniz. Bu arada except: diyip biraktigimiza dikkat edin kendisi catch-all oluyor.

import sys
try:
    open("ahmet.txt")
except: # catch *all* exceptions
    e = sys.exc_info()[0]
    print ( "

Error: %s

" % e )

Bu arada “raise”  diye guzel bir statement var , super istediginiz gibi ValueError , NameError gibi exceptionlari uretebilirsiniz ama bunu bence en guzel yazilimcinin kendi istedigi execption’i yaratabilmesi

raise icin ilgili linkden bir ornek aldim http://zetcode.com/lang/python/exceptions/ . Burada “BFoundError” adli bir sub-class yaratiliyor (Exception class’indan turuyor) , sonra default arg uzerine yazilaraktan __init__ yeni constractor  yaratiliyor, pos degeri bu class a variable olarak atanip ilgili class calistiriliyor

#!/usr/bin/python

# b.py

class BFoundError(Exception):
def __init__(self, value):
print "BFoundError: b character found at position %d" % value

string = "You make me want to be a better man."

pos = 0
for i in string:
if i == 'b':
raise BFoundError, pos
pos = pos + 1

Olay bu !

Posted on 05/05/2016, in Python and tagged , , , , , . Bookmark the permalink. Leave a comment.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: