python中“except Exception as e”是什么意思?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27517519/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What does ''except Exception as e'' mean in python?
提问by lxjhk
The typical structure for exception handling is below:
异常处理的典型结构如下:
try:
pass
except Exception, e:
raise
else:
pass
finally:
pass
May I know what does except Exception, e:
orexcept Exception as e:
mean?
Typically I will use print (e)
to print the error message but I am wondering what the program has done to generate the e.
我想知道是什么except Exception, e:
或者except Exception as e:
是什么意思?通常我会print (e)
用来打印错误消息,但我想知道程序做了什么来生成 e.txt 文件。
If I were to construct it in another way (below), how would it be like?
如果我以另一种方式构建它(如下),它会是什么样子?
except Exception:
e = Exception.something
What should the method be to replace the something
?
应该用什么方法来替换something
?
When the body of code under try
gives no exception, the program will execute the code under else
. But, what does finally
do here?
当下面的代码体try
没有异常时,程序将执行下面的代码else
。但是,finally
在这里做什么?
采纳答案by Max Noel
except Exception as e
, or except Exception, e
(Python 2.x only) means that it catches exceptions of type Exception
, and in the except:
block, the exception that was raised (the actual object, not the exception class) is bound to the variable e
.
except Exception as e
,或except Exception, e
(仅限 Python 2.x)表示它捕获类型为 的异常Exception
,并且在except:
块中,引发的异常(实际对象,而不是异常类)绑定到变量e
。
As for finally
, it's a block that alwaysgets executed, regardless of what happens, after the except
block (if an exception is raised) but always before anything else that would jump out of the scope is triggered (e.g. return
, continue
or raise
).
至于finally
,它是一个总是被执行的块,无论发生什么,在except
块之后(如果引发异常)但总是在触发任何其他会跳出范围的东西之前(例如return
,continue
或raise
)。