Python - 在try-except-else中捕获异常的简便方法

时间:2016-12-23 00:19:09

标签: python

在Python中,我们可以使用as来捕获except语句中的异常实例。但是,在else之后的try语句中似乎没有一种简单的方法可以做同样的事情。为了更清楚,请参阅下面的代码。

try:
    raise Exception('Foo')
except ValueError as valueError:
    print(valueError)
    print('I can capture the exception instance with "as" keyword')
else:    # Cannot use "as" here
    print('Some exception other than ValueError')
    print('How can I capture the exception in order to, e.g. print its message?')

有什么想法吗?

2 个答案:

答案 0 :(得分:4)

try:
    raise Exception('Foo')
except ValueError as valueError:
    print(valueError)
    print('I can capture the exception instance with "as" keyword')
except Exception as e:  
    print(e)
    print('Some exception other than ValueError')
else:
    print('no exception raised')

答案 1 :(得分:4)

使用多个except子句:

要么像这样:

try:
    f = open('myfile.txt')
    s = f.readline()
    i = int(s.strip())
except OSError as err:
    print("OS error: {0}".format(err))
except ValueError:
    print("Could not convert data to an integer.")
except:
    print("Unexpected error:", sys.exc_info()[0])
    raise

或者将例外聚集在一起:

except (RuntimeError, TypeError, NameError):
    pass