在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?')
有什么想法吗?
答案 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