简体   繁体   English

我如何知道在Python中捕获哪些异常

[英]How do I know which exceptions to catch in Python

In Python, I've read that it's better (and easier) to catch execptions, rather than check first, so that's what I'm trying to do. 在Python中,我已经读过捕获exec更好(也更容易),而不是先检查,所以这就是我想要做的。

My script opens and parses an XMLs file using 我的脚本打开并使用解析XML文件

xml.dom.minidom.parse(xml_file_path)

so I'm catching 所以我抓住了

xml.parsers.expat.ExpatError

but if the file doesn't exist, I get a FileNotFoundError exception, so I obviously need to catch that too. 但是如果文件不存在,我会得到一个FileNotFoundError异常,所以我显然也需要抓住它。

I know that I shouldn't really be catching all exceptions, but how can I know what exceptions I should be catching for a function like parse()? 我知道我不应该抓住所有异常,但我怎么知道我应该为像parse()这样的函数捕获哪些异常?

You can consult documentation of library you use. 您可以查阅您使用的库的文档。 And even better you can write a test where you trigger exception first . 甚至可以更好地编写一个触发异常的测试。 Then you will know exactly what exception you need to catch (and have another test to guard you in the future). 然后,您将确切地知道需要捕获的异常(并在将来进行另一项测试以保护您)。

A good place to start are the ' Built-in Exceptions ' of Python. 一个好的起点是Python的“ 内置异常 ”。 With some study you can tell what operation can cause which exception. 通过一些研究,您可以判断哪些操作可能导致哪个异常。 The documentation is also particularly useful as it provides practical examples. 该文档也特别有用,因为它提供了实际的例子。

Specifically in your case, you are performing file Input/Output operations (IO) and IO operations are handled generally as: 特别是在您的情况下,您正在执行文件输入/输出操作(IO)和IO操作通常处理为:

try:
    with open('path_to_file', 'permission') as f:
        #do something with the file
except IOError as e:
    print e

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM