如何将函数调用期间收到的错误返回给main?
我有一些简单的东西,例如:
def check(file):
if not os.path.exists(file): # returns false by itself, but I want error
return -1
调用时,它只返回调用.py
,程序结束。但我试图返回发生的事情(即文件不存在)。提出异常更合适吗?
答案 0 :(得分:1)
如果您确实想要提出异常而不是在文件不存在时返回-1
,那么您可以跳过check()
并直接转到{{1或者你真正想要对文件做什么。
实际引发异常的正确方法是让它被引发。这样做:
open()
如果你想在打开之前明确检查,这将引发实际的错误对象:
def check_and_open(file):
# raises FileNotFoundError automatically
with open('xyz', 'r') as fp:
fp.readlnes() # or whatever
此版本的结果是:
def check(file):
try:
with open(file, 'r') as fp:
# continue doing something with `fp` here or
# return `fp` to the function which wants to open file
pass
except FileNotFoundError as e:
# log error, print error, or.. etc.
raise e # and then re-raise it
此外,请注意,正如>>> check('xyz')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 9, in check
File "<stdin>", line 3, in check
FileNotFoundError: [Errno 2] No such file or directory: 'xyz'
>>>
所做的那样,与其他答案一样,会打破raise FileNotFoundError(file)
实际提出的方式:
显式提升(文件名被视为错误消息):
FileNotFoundError
Python如何实际提出它:
>>> raise FileNotFoundError('xyz')
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
FileNotFoundError: xyz
>>>
答案 1 :(得分:0)
您可以raise
异常(内置库中使用FileNotFoundError
),但如果您尝试使用不存在的文件,则会引发FileNotFoundError
异常默认情况下。
然后,在使用此功能时,处理您的异常:
import os
def check(file):
if not os.path.exists(file):
raise FileNotFoundError(file)
if __name__ == '__main__':
try:
check(os.path.join('foo', 'bar'))
except FileNotFoundError:
print('File was not found')
答案 2 :(得分:0)
(作为我的previous answer的替代方案。)
另一种更正确的方式来执行check()
如果你想在做其他事情之前明确检查 - 使用os.stat()
实际上没有打开文件:
import os
def check(file):
try:
os.stat(file)
# continue doing something here or
# return to the function which wants to open file
except FileNotFoundError as e:
# log error, print error, or.. etc.
raise e # and then re-raise it
此版本的结果是:
>>> check('xyz')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 8, in check
File "<stdin>", line 3, in check
FileNotFoundError: [WinError 2] The system cannot find the file specified: 'xyz'
>>>
请注意,与prev:[Errno 2] No such file or directory: 'xyz'