Python
 Computer >> コンピューター >  >> プログラミング >> Python

リスト内包表記でPython例外をキャッチする方法は?


Pythonには例外を処理または無視できる組み込み関数がないため、リスト内包には1つ以上の式が含まれているため、リスト内包のすべての例外を処理することはできません。ステートメントのみが例外をキャッチ/無視/処理できます。

例外が発生しやすい部分式の評価を関数に委任することは、実行可能な回避策の1つです。その他は、例外を発生させる可能性のある値のチェックです。

この問題を処理する方法は、次のコードを使用することです。

foo = (5,7,1,0,9)
def bar(self):
try:
return [1/i for i in foo]
except ZeroDivisionError as e:
print e
bar(foo)
出力
integer division or modulo by zero
Process finished with exit code 0

  1. Pythonで例外を処理する方法は?

    Pythonで例外を処理する最も簡単な方法は、「try-except」ブロックを使用することです。 例 try: fob = open("test.txt", "r") fob.write("This is my test file for exception handling!!") except IOError: print "Error: can\'t find the file or read data" else: print "Write operation is performed

  2. ループ内でPython例外を処理する方法は?

    次のように書き直すことで、コードの例外を作成できます a=[] foo = 'redbullz' try: for i in foo: a.append(i) print a[8] except Exception as e: print e 次の出力が得られます list index out of range Process finished with exit code 0