2016-07-26 102 views
-2

我写了一个尝试,除了块,我现在认识到是一个坏主意,因为它不断抛出难以调试的'盲'异常。问题是,我不知道如何去写另一种方式,除了通过每个被调用的方法并手动读取所有异常并为每个方法创建一个案例。我怎样才能解决这个尝试除了块?

你会如何构造这段代码?

def get_wiktionary_audio(self): 
    '''function for adding audio path to a definition, this is meant to be run before trying to get a specific URL''' 
    #this path is where the audio will be saved, only added the kwarg for testing with a different path 
    path="study_audio/%s/words" % (self.word.language.name) 
    try: 

     wiktionary_url = "http://%s.wiktionary.org/wiki/FILE:en-us-%s.ogg" % (self.word.language.wiktionary_prefix, self.word.name) 
     wiktionary_page = urllib2.urlopen(wiktionary_url) 
     wiktionary_page = fromstring(wiktionary_page.read()) 
     file_URL = wiktionary_page.xpath("//*[contains(concat(' ', @class, ' '), ' fullMedia ')]/a/@href")[0] 
     file_number = len(self.search_existing_audio()) 
     relative_path = '%s/%s%s.ogg' % (path, self.word.name, file_number) 
     full_path = '%s/%s' % (settings.MEDIA_ROOT, relative_path) 
     os.popen("wget -q -O %s 'http:%s'" % (full_path, file_URL)) 

    except: 
     return False 

    WordAudio.objects.create(word=self.word, audio=relative_path, source=wiktionary_url) 
    return True 
+3

*“手动读取所有异常并为每个异常做出判断”* ...这就是您需要执行的操作。盲目捕捉异常并不是一个好主意。 – solarissmoke

+2

@solarissmoke ...只捕获你可以处理的异常。并非每个例外。有些需要通过..或者,除了块将比try块更长。使用异常来添加更多的代码是Python编码风格。 – Merlin

+1

这里的信息太少了。问题是,你想在什么情况下返回False?代码不好的原因是它会聚集太多东西,并返回False来解决所有可能的错误。要决定如何更好地编写代码,您需要更详细地考虑代码中可能发生的情况以及您想要做什么。 – BrenBarn

回答

0

通常情况下,异常会附带可用于查明问题的错误字符串。你可以像这样访问该值:

try: 
    # code block 
except Exception as e: 
    print str(e) 

您还可以打印任何错误消息一起是什么级别的异常使用repr方法:

try: 
    # code block 
except Exception as e: 
    print repr(e) 
+0

您还可以导入回溯,然后在except块中调用traceback.print_exc()以打印异常信息和堆栈跟踪 –

-1

首先你的代码是联合国Python化。您正在使用'self'作为功能。 “self"通常保留给一个类,所以在阅读你的代码时,感觉不自然;其次,我的风格是排列"="符号以提高可读性,我的建议是重新开始 - 使用标准的pythonic约定。经历蟒蛇教程。

抛出异常的早期,往往-only代码停止运行时,你也可以将一些命名的try/except外块。

def get_wiktionary_audio(self): 
    '''function for adding audio path to a definition, this is meant to be run before trying to get a specific URL''' 
    #this path is where the audio will be saved, only added the kwarg for testing with a different path 
    path    = "study_audio/%s/words" % (self.word.language.name) 
    try: 

     wiktionary_url = "http://%s.wiktionary.org/wiki/FILE:en-us-%s.ogg" % (self.word.language.wiktionary_prefix, self.word.name) 
     wiktionary_page = urllib2.urlopen(wiktionary_url) 
     wiktionary_page = fromstring(wiktionary_page.read()) 
     file_URL  = wiktionary_page.xpath("//*[contains(concat(' ', @class, ' '), ' fullMedia ')]/a/@href")[0] 
     file_number  = len(self.search_existing_audio()) 
     relative_path = '%s/%s%s.ogg' % (path, self.word.name, file_number) 
     full_path  = '%s/%s' % (settings.MEDIA_ROOT, relative_path) 
     os.popen("wget -q -O %s 'http:%s'" % (full_path, file_URL)) 

    except Exception as e : print e 


    WordAudio.objects.create(word=self.word, audio=relative_path, source=wiktionary_url) 
    return True 
+1

'self'是函数的参数,这可能是一种方法。 – BrenBarn

+0

在上面的代码中,“自我”是一种方法吗? – Merlin

+1

我在说'get_wiktionary_audio'可能是一种方法。 (提问者可能只是省略了封闭类,因为它与try/except块的问题没有密切关系。) – BrenBarn

0

的一种方式,我喜欢去它配置Python日志记录并记录输出结果,这为您在日志输出方面提供了很大的灵活性,下面的例子记录了异常回溯:

import traceback 
import logging 

logger = logging.getLogger(__name__) 

try: 
    ... 
except Exception as e: 
    logger.exception(traceback.format_exc()) # the traceback 
    logger.exception(e) # just the exception message 
相关问题