There are a lot of other uses for
exceptions besides handling actual
error conditions. A common use in the
standard Python library is to try to
import a module, and then check
whether it worked. Importing a module
that does not exist will raise an
ImportError exception. You can use
this to define multiple levels of
functionality based on which modules
are available at run-time, or to
support multiple platforms (where
platform-specific code is separated
into different modules).
The next example demonstrates how to
use an exception to support
platform-specific functionality.
使用logger时,您必须实现错误的日志记录。
在Python中,默认情况下,错误只记录到控制台。
所以,如果您想使用logger,就必须添加逻辑来捕获和记录错误。在
try except
块是在Python上处理导入的常用方法。在引用Dive into Python:
与IDE的日志(甚至是从控制台或终端运行python文件)的区别在于,一旦捕捉到异常,脚本就会立即中断。在
如果您想获取异常并在它发生后做一些事情,例如记录它,那么您需要使用“try except”块。在
我不知道你为什么要避免使用“try except”块,因为它是语言的一个基本特性,就像任何其他决策块(“if”、“while”、“for”等等)一样。在
试着把它看作一个常见的“如果”语句:
相关问题 更多 >
编程相关推荐