ホームページ  >  記事  >  バックエンド開発  >  Pythonの例外について(Exception)

Pythonの例外について(Exception)

不言
不言オリジナル
2018-04-24 16:14:493494ブラウズ

この記事の内容は Python の例外に関するものです。必要な方は参考にしてください。

例外とは、プログラム内の例外と違反を指します。例外メカニズムとは、プログラム内でエラーが発生した後のプログラムの処理方法を指します。エラーが発生すると、プログラムの実行フローが変更され、プログラムの制御が例外処理に移ります。以下の記事は主に Python の例外に関する関連情報をまとめたものです。必要な方は参考にしてください。

はじめに

Exception クラスは、StandardError、StopIteration、GeneratorExit、Warning およびその他の例外クラスを含む、一般的に使用される例外クラスです。 Python の例外は継承構造を使用して作成されます。基本クラスの例外は例外ハンドラーでキャプチャできます。また、さまざまなサブクラスの例外は Python の try...Except ステートメントを使用してキャプチャでき、例外句は例外ハンドラーの後に定義されます。 try 句。

Pythonの例外処理

例外処理のステートメント構造

try:
 <statements>  #运行try语句块,并试图捕获异常
except <name1>:
 <statements>  #如果name1异常发现,那么执行该语句块。
except (name2, name3):
 <statements>  #如果元组内的任意异常发生,那么捕获它
except <name4> as <variable>:
 <statements>  #如果name4异常发生,那么进入该语句块,并把异常实例命名为variable
except:
 <statements>  #发生了以上所有列出的异常之外的异常
else:
<statements>   #如果没有异常发生,那么执行该语句块
finally:
 <statement>   #无论是否有异常发生,均会执行该语句块。

説明

  • はオプションであり、 0 または複数を除く、ただしelse が発生する場合は、少なくとも 1 つの例外が存在する必要があります。

  • 例外をどのように指定するかに関係なく、例外は常にインスタンス オブジェクトによって識別され、ほとんどの場合、任意の瞬間にアクティブ化されます。例外がプログラム内のどこかの例外句によってキャッチされると、別の raise ステートメントまたはエラーによって再呼び出されない限り、その例外は無効になります。

raise ステートメント

raise ステートメントは、手動で例外をスローするために使用されます。いくつかの呼び出し形式があります。

  • raise #インスタンスは、raise ステートメントの前または raise ステートメント内で作成できます。

  • raise #Python はクラスのインスタンスを暗黙的に作成します

  • raise name(value) #例外をスローするときは、追加情報を提供しますvalue

  • raise #最後に生成された例外を再スローします

  • E

から例外を発生させます。例:

raise ValueError with追加情報: raise ValueError('正の値のみを受け入れることができます')ValueError: raise ValueError('we can only accept positive values')

当使用from的时候,第二个表达式指定了另一个异常类或实例,它会附加到引发异常的__cause__属性。如果引发的异常没有捕获,Python把异常也作为标准出错消息的一部分打印出来:

比如下面的代码:

try:
 1/0
except Exception as E:
 raise TypeError(&#39;bad input&#39;) from E

执行的结果如下:

Traceback (most recent call last):
 File "hh.py", line 2, in <module>
 1/0
ZeropisionError: pision by zero

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
 File "hh.py", line 4, in <module>
 raise TypeError(&#39;bad input&#39;) from E
TypeError: bad input

assert语句

assert主要用来做断言,通常用在单元测试中较多,到时候再做介绍。

with...as语句

with语句支持更丰富的基于对象的协议,可以为代码块定义支持进入和离开动作。

with语句对应的环境管理协议要求如下:

  • 环境管理器必须有__enter____exit__方法。

       __enter__方法会在初始化的时候运行,如果存在ass子在, __enter__函数的返回值会赋值给as子句中的变量,否则,直接丢弃。

       代码块中嵌套的代码会执行。

       如果with代码块引发异常, __exit__(type,value,traceback)方法就会被调用(带有异常细节)。这些也是由 sys.exc_info返回的相同值.如果此方法返回值为假,则异常会重新引发。否则,异常会终止。正常 情况下异常是应该被重新引发,这样的话才能传递到with语句之外。

       如果with代码块没有引发异常, __exit__方法依然会被调用,其type、value以及traceback参数都会以None传递。

下面为一个简单的自定义的上下文管理类。

class Block:
 def __enter__(self):
  print(&#39;entering to the block&#39;)
  return self
 
 def prt(self, args):
  print(&#39;this is the block we do %s&#39; % args)

 def __exit__(self,exc_type, exc_value, exc_tb):
  if exc_type is None:
   print(&#39;exit normally without exception&#39;)
  else:
   print(&#39;found exception: %s, and detailed info is %s&#39; % (exc_type, exc_value))
  return False

with Block() as b:
 b.prt(&#39;actual work!&#39;)
 raise ValueError(&#39;wrong&#39;)

如果注销到上面的raise语句,那么会正常退出。

在没有注销掉该raise语句的情况下,运行结果如下:

entering to the block
this is the block we do actual work!
found exception: <class &#39;ValueError&#39;>, and detailed info is wrong
Traceback (most recent call last):
 File "hh.py", line 18, in <module>
 raise ValueError(&#39;wrong&#39;)
ValueError: wrong

异常处理器

如果发生异常,那么通过调用sys.exc_info()

when fromを使用する場合、2番目の式は、例外を発生させた __cause__ 属性に追加される別の例外クラスまたはインスタンスを指定します。発生した例外がキャッチされない場合、Python は標準エラー メッセージの一部として例外を出力します。
たとえば、次のコード:

|Exception Name|Description|
|BaseException|Root class for all exceptions|
| SystemExit|Request termination of Python interpreter|
|KeyboardInterrupt|User interrupted execution (usually by pressing Ctrl+C)|
|Exception|Root class for regular exceptions|
| StopIteration|Iteration has no further values|
| GeneratorExit|Exception sent to generator to tell it to quit|
| SystemExit|Request termination of Python interpreter|
| StandardError|Base class for all standard built-in exceptions|
|  ArithmeticError|Base class for all numeric calculation errors|
|   FloatingPointError|Error in floating point calculation|
|   OverflowError|Calculation exceeded maximum limit for numerical type|
|   ZeropisionError|pision (or modulus) by zero error (all numeric types)|
|  AssertionError|Failure of assert statement|
|  AttributeError|No such object attribute|
|  EOFError|End-of-file marker reached without input from built-in|
|  EnvironmentError|Base class for operating system environment errors|
|   IOError|Failure of input/output operation|
|   OSError|Operating system error|
|    WindowsError|MS Windows system call failure|
|    ImportError|Failure to import module or object|
|    KeyboardInterrupt|User interrupted execution (usually by pressing Ctrl+C)|
|   LookupError|Base class for invalid data lookup errors|
|    IndexError|No such index in sequence|
|    KeyError|No such key in mapping|
|   MemoryError|Out-of-memory error (non-fatal to Python interpreter)|
|   NameError|Undeclared/uninitialized object(non-attribute)|
|    UnboundLocalError|Access of an uninitialized local variable|
|   ReferenceError|Weak reference tried to access a garbage collected object|
|   RuntimeError|Generic default error during execution|
|    NotImplementedError|Unimplemented method|
|   SyntaxError|Error in Python syntax|
|    IndentationError|Improper indentation|
|     TabErrorg|Improper mixture of TABs and spaces|
|   SystemError|Generic interpreter system error|
|   TypeError|Invalid operation for type|
|   ValueError|Invalid argument given|
|    UnicodeError|Unicode-related error|
|     UnicodeDecodeError|Unicode error during decoding|
|     UnicodeEncodeError|Unicode error during encoding|
|     UnicodeTranslate Error|Unicode error during translation|
|  Warning|Root class for all warnings|
|   DeprecationWarning|Warning about deprecated features|
|   FutureWarning|Warning about constructs that will change semantically in the future|
|   OverflowWarning|Old warning for auto-long upgrade|
|   PendingDeprecation Warning|Warning about features that will be deprecated in the future|
|   RuntimeWarning|Warning about dubious runtime behavior|
|   SyntaxWarning|Warning about dubious syntax|
|   UserWarning|Warning generated by user code|

実行結果は次のとおりです:

rrreee

assert ステートメント

🎜🎜🎜assert は主にアサーションを行うために使用され、後で紹介する単体テストでよく使用されます。 🎜🎜🎜with...as ステートメント 🎜🎜🎜🎜with ステートメントは、コード ブロックのサポート開始および終了アクションを定義できる、より豊富なオブジェクトベースのプロトコルをサポートします。 🎜🎜🎜with ステートメントに対応する環境管理プロトコルの要件は次のとおりです。 🎜🎜🎜🎜 環境マネージャーには、__enter__ メソッドと __exit__ メソッドが必要です。 _ __ ENTER __ メソッドは、ASS 子がある場合、AS 句の変数を割り当て、それ以外の場合は直接破棄されます。 。 🎜🎜🎜 コードブロックにネストされたコードが実行されます。 🎜🎜🎜 with コード ブロックが例外をスローした場合、__exit__(type,value,traceback) メソッドが (例外の詳細とともに) 呼び出されます。これらは、sys.exc_info によって返される値と同じです。このメソッドが false を返す場合、例外が再発生します。それ以外の場合は異常終了します。通常の状況では、例外を with ステートメントの外に渡すことができるように、例外を再発生させる必要があります。 🎜🎜🎜 with コード ブロックが例外を発生させない場合でも、__exit__ メソッドは呼び出され、その型、値、およびトレースバック パラメーターは None として渡されます。 🎜🎜🎜以下は、単純なカスタム コンテキスト管理クラスです。 🎜🎜🎜rrreee🎜🎜🎜上記の raise ステートメントからログアウトすると、正常に終了します。 🎜🎜🎜 raise ステートメントをログアウトしないと、実行結果は次のようになります: 🎜🎜🎜rrreee🎜🎜🎜🎜例外ハンドラー🎜🎜🎜🎜 例外が発生した場合は、sys.exc_info() コードを呼び出します。 > 関数。3 つの要素を含むタプルを返すことができます。 最初の要素は例外を発生させたクラスであり、2 番目の要素は実際に発生したインスタンスであり、3 番目の要素であるトレースバック オブジェクトは、例外が最初に発生したときの呼び出しのスタックを表します。すべてが正常であれば、3 None が返されます。 🎜🎜🎜PythonのBuiltinsモジュールで定義された例外🎜🎜🎜🎜🎜rrreee🎜🎜🎜関連推奨事項: 🎜🎜🎜🎜Pythonの例外処理メソッドの詳細な画像とテキストの説明🎜🎜🎜🎜<p class="clearfix"><span class="jbTestPos"></span></p>

以上がPythonの例外について(Exception)の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

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