我有一個基於GUI的項目。我想遠離它到代碼本身和GUI部分。設計一個健全檢查
這是我的代碼: Main.py
:
class NewerVersionWarning(Exception):
def __init__(self, newest, current=__version__):
self.newest = newest
self.current = current
def __str__(self):
return "Version v%s is the latest version. You have v%s." % (self.newest, self.current)
class NoResultsException(Exception):
pass
# ... and so on
def sanity_check():
"Sanity Check for script."
try:
newest_version = WebParser.WebServices.get_newestversion()
if newest_version > float(__version__):
raise NewerVersionWarning(newest_version)
except IOError as e:
log.error("Could not check for the newest version (%s)" % str(e))
if utils.get_free_space(config.temp_dir) < 200*1024**2: # 200 MB
drive = os.path.splitdrive(config.temp_dir)[0]
raise NoSpaceWarning(drive, utils.get_free_space(config.temp_dir))
# ... and so on
現在,在圖形用戶界面的一部分,我只是調用中的功能的try-except塊:
try:
Main.sanity_check()
except NoSpaceWarning, e:
s = tr("There are less than 200MB available in drive %s (%.2fMB left). Application may not function properly.") % (e.drive, e.space/1024.0**2)
log.warning(s)
QtGui.QMessageBox.warning(self, tr("Warning"), s, QtGui.QMessageBox.Ok)
except NewerVersionWarning, e:
log.warning("A new version of iQuality is available (%s)." % e.newest)
QtGui.QMessageBox.information(self, tr("Information"), tr("A new version of iQuality is available (%s). Updates includes performance enhancements, bug fixes, new features and fixed parsers.<br /><br />You can grab it from the bottom box of the main window, or from the <a href=\"%s\">iQuality website</a>.") % (e.newest, config.website), QtGui.QMessageBox.Ok)
在目前的設計中,檢查停止在第一個警告/例外。當然,一個異常應該停止代碼,但是一個警告應該只顯示一條消息給用戶並在之後繼續。我該如何設計它?
一個簡單的方法將只是如果遇到一個警告(將其添加到警告或東西的清單),以不引發異常。 Python使用異常方式過於寬鬆地使用IMO,並且在更簡單的解決方案可用時限制人們使用使用異常。 – NullUserException