ホームページ  >  記事  >  バックエンド開発  >  Pythonの例外処理を詳しく解説

Pythonの例外処理を詳しく解説

高洛峰
高洛峰オリジナル
2016-10-20 09:46:301310ブラウズ

このセクションでは主に、Python における例外処理の原則と主な形式を紹介します。


1. 例外とは


例外オブジェクトは、Python で異常な状況を表すために使用されます。プログラムの実行中にエラーが発生すると、例外がスローされます。例外オブジェクトが処理されない、またはキャッチされない場合、プログラムはバックトラックして実行を終了します。


2. 例外をスローする


raise ステートメント、raise の後に例外例外クラスまたは例外サブクラスを続けると、例外の括弧内に例外情報を追加することもできます。


>>>raise Exception('message')


注: Exception クラスは、すべての例外クラスの基本クラスです。次のように、このクラスに基づいて独自の定義された例外クラスを作成することもできます。 :


class SomeCustomException(Exception): pass


3. 例外のキャッチ (try/excel ステートメント)


try/excel ステートメントは、try ステートメント ブロック内のエラーを検出するために使用されます。例外ステートメントが例外情報を取得して処理できること。


try ステートメントブロックで複数の例外をスローできます:

try:
     x = input('Enter the first number: ')
     y = input('Enter the second number: ')
     print x/y
 except ZeroDivisionError:
     print "The second number can't be zero!"
 except TypeError:
     print "That wasn't a number, was it?"


1 つの例外ステートメントで複数の例外をキャプチャできます:

try:
     x = input('Enter the first number: ')
     y = input('Enter the second number: ')
     print x/y
 except (ZeroDivisionError, TypeError, NameError):  #注意except语句后面的小括号
     print 'Your numbers were bogus...'

キャプチャされた例外オブジェクトにアクセスし、例外情報を出力します:

try:
     x = input('Enter the first number: ')
     y = input('Enter the second number: ')
     print x/y
 except (ZeroDivisionError, TypeError), e:
     print e

予測できない例外の見逃しを防ぐために、すべての例外をキャプチャします。

try:
     x = input('Enter the first number: ')
     y = input('Enter the second number: ')
     print x/y
 except :
     print 'Someting wrong happened...'

4. else 句。 Try ブロックで例外がスローされない場合は、Except 句を使用するだけでなく、else 句も使用できます。

while 1:
     try:
         x = input('Enter the first number: ')
         y = input('Enter the second number: ')
         value = x/y
         print 'x/y is', value
     except:
         print 'Invalid input. Please try again.'
     else:
         break

上記のコード ブロックが実行された後、ユーザーが入力した x 値と y 値が正当な場合、else 句が実行され、プログラムは実行を終了できます。


5.最後に条項。 try 句で例外が発生するかどうかに関係なく、finally 句は必ず実行され、else 句と併用することもできます。多くの場合、finally 句は、プログラムの最後にファイルまたはネットワーク ソケットを閉じるために使用されます。

try:
     1/0
 except:
     print 'Unknow variable'
 else:
     print 'That went well'
 finally:
     print 'Cleaning up'

6. 例外と関数

関数内で例外が発生し、処理されなかった場合、その例外は関数が呼び出された場所に渡されます。メインプログラムに渡され、スタックされます。 追跡フォームは終了します。

def faulty():
    raise Exception('Someting is wrong!')
def ignore_exception():
    faulty()
      
def handle_exception():
    try:
        faulty()
    except Exception, e:
        print 'Exception handled!',e
  
handle_exception()
ignore_exception()

上記のコード ブロックでは、関数 handle_Exception() が fast() を呼び出した後、faulty() 関数は例外をスローし、handle_Exception() に渡されるため、try/excel ステートメントによって処理されます。 ignare_Exception() 関数には、faulty() の例外処理がないため、例外スタック トレースが発生します。

注: 条件文 if/esle は例外処理と同じ機能を実現できますが、条件文は不自然で読みにくい場合があります。

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。