2017-06-29 8 views
0

関数呼び出し中に受け取ったエラーをmainに戻すにはどうすればよいですか?関数からエラーが返されました

私はこのような単純なもの持っている:と呼ばれる、それだけで呼び出す.pyに戻り、プログラムが終了すると

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

を。しかし、私は何が起こったかを返そうとしています(すなわち、ファイルは存在しません)。より適切な例外を提起していますか?あなたは、デフォルトで提起FileNotFoundError例外を取得します存在しないファイルを使用しようとするでしょう場合が

+1

[Pythonで例外を処理する方法](https://wiki.python.org/moin/HandlingExceptions) –

+2

をご覧になりたい場合があります。これはソフトウェアの設計者の責任です。ファイルが存在しないために例外を発生させたい場合は、-1を返す代わりに、自分で例外を発生させます。 – idjaw

+0

"何が起こったか"は、 'os.path.exists(file)'が 'False'を返したことです。呼び出し可能な '.py'ファイルは、この可能な戻り値を処理するように構造化されるべきです。そうしないと、エラーが発生します(これは呼び出し側の手続きに持ち込まれます)。 –

答えて

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:明示的に上げる

が(ファイル名はERRメッセージとして考えられます):それは実際にはPythonで上げていますどのように

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

>>> 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はライブラリに内蔵され使用されている)を。

この機能を使用するときに、あなたの例外を処理:

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' 
>>> 

注:[Errno 2] No such file or directory: 'xyz'

関連する問題