[英]Python 2.7 exception handling
我正在使用python 2.7,我已经建立了一个自定义的异常类,并且当我捕获到该异常时程序不会停止。
这是我的代码片段:
try:
result = OsUtils.is_os_name_valid(allowedSystems)
print "This is the result: {0}".format(result)
if result is False:
raise ErrorUnsupportedOsSystemException(OsUtils.get_os_type())
except ErrorUnsupportedOsSystemException as e:
print "({0}) {1}, ".format(e.os_type, e.message)
except IOError as e:
print "I/O error ({0}) : {1}".format(e.errno, e.strerror)
except:
print "Unexpected error:", sys.exc_info()[0]
raise
print "Test"
这是异常类:
class ErrorUnsupportedOsSystemException(Exception):
message = "Error: unsupported system!!"
def __init__(self, os_type):
self.os_type = os_type
pass
这是我得到的输出:
This is the result: False
(posix) Error: unsupported system!!,
Test
不应打印“测试”。
尝试这样的事情。 使它与您的代码一起使用。
import sys
try:
things...
except ErrorThatJustShouldBeLogged as e:
log an error or something
except ErrorThatShouldExitProgram as e:
sys.exit(0)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.