2011-04-09 3 views
0
import httplib 
import re 

md5 = raw_input('Enter MD5: ') 

conn = httplib.HTTPConnection("www.md5.rednoize.com") 
conn.request("GET", "?q="+ md5) 
try: 
    response = conn.getresponse() 
    data = response.read() 
    result = re.findall('<div id="result" >(.+?)</div', data) 
    print result 
except: 
    print "couldnt find the hash" 

raw_input() 

나는 아마 내가 틀린 코드를 구현하고 있음을 알고 있지만 어떤 예외를 사용해야합니까? 해시를 찾을 수 없으면 예외를 발생시키고 "해시를 찾을 수 없습니다"라는 메시지를 인쇄하십시오.예외를 사용하여 md5 검색

+0

나는에 대한 IOError' 제외하고'같은 이름 예외의 사용을 권장하고 싶습니다 예외 처리 (파이썬 3은 이름이 지정되지 않은 예외도 오류로 표시합니다). 이렇게하면이 특정 문제를 더 잘 이해하는 데 도움이됩니다. –

답변

2

re.findall은 예외를 발생시키지 않으므로 결과를 확인하는 방법이 아닐 수 있습니다. 당신은 정말이 예외를 당신이 그것을 정의 할 필요가있다 싶은 경우에 대신

result = re.findall('<div id="result" >(.+?)</div', data) 
if result: 
    print result 
else: 
    print 'Could not find the hash' 
1

뭔가를 작성할 수

class MyError(Exception): 
    def init(self, value): 
     self.value = value 
    def str(self): 
     return repr(self.value)

try: response = conn.getresponse() data = response.read() result = re.findall('(.+?)</div', data) if not result: raise MyError("Could not find the hash") except MyError: raise