2017-06-29 109 views
0

如何將函數調用回主函數期間收到的錯誤?函數返回遇到的錯誤

我有一些簡單的如:

def check(file): 
    if not os.path.exists(file): # returns false by itself, but I want error 
     return -1 

調用時,它只是返回到調用.py和程序結束。但我試圖返回發生的事情(即文件不存在)。提出一個更合適的例外?

+1

也許你想看看[如何處理Python中的異常](https://wiki.python.org/moin/HandlingExceptions) –

+2

這取決於你作爲軟件的設計者。如果因爲文件不存在而想引發異常,則不要返回-1,而要自己引發異常。 – idjaw

+0

「發生了什麼」是'os.path.exists(file)'返回'False'。調用'.py'文件應該被構造來處理這個可能的返回值,或者你應該引發一個錯誤(這會引發調用過程)。 –

回答

1

如果你想提高,而不是返回-1一個異常時,該文件不存在,你可以跳過check()和直接去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實際上提出:

明確提高(文件名被視爲錯誤號):

>>> raise FileNotFoundError('xyz') 
Traceback (most recent call last): 
    File "<stdin>", line 2, in <module> 
FileNotFoundError: xyz 
>>> 

如何它實際上是由Python中提出:

>>> fp = open('xyz', 'r') 
Traceback (most recent call last): 
    File "<stdin>", line 2, in <module> 
FileNotFoundError: [Errno 2] No such file or directory: 'xyz' 
>>> 
>>> # or with `with`: 
... with open('xyz', 'r') as fp: 
...  fp.readlnes() 
... 
Traceback (most recent call last): 
    File "<stdin>", line 2, in <module> 
FileNotFoundError: [Errno 2] No such file or directory: 'xyz' 
>>> 
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') 
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' 
>>> 

注意,錯誤是有點不同,這裏的VS上一篇:[Errno 2] No such file or directory: 'xyz'