1

在 C++ 中,为了使代码在出现异常时保持健壮,通常需要依赖这样一个事实,即保证一些简单的操作永远不会失败(因此永远不会抛出异常)。这些操作的示例包括分配整数和交换标准容器。

Python 中是否有任何操作可以提供这种无失败保证?

4

1 回答 1

3

Python is a higher-level language than C and C++. Anything can involve code execution behind the scenes, and no name is exempt from looking up its current, possibly overridden value. It might be possible to identify some operations that are guaranteed never to raise an exception, but I suspect that set of operations would be so small that it provides no benefit over the usual assumption that anything can raise an exception at any time.

And the identification of those operations would require limiting your Python environment. For example, you can assign a trace function which is invoked for every line of your Python program. With a suitably crafted trace function, even 1+1 could raise an exception. So do we assume that there is no trace function? What about redefining builtins?

Practically speaking, you need to adopt a different mindset for Python: exceptions happen, and you can't know ahead of time what they might be. As Mark Amery says in the comments, C++ needs to avoid memory leaks and uninitialized variables, which are not issues in Python.

于 2013-01-27T13:42:40.060 回答