Object-oriented-python-exception-classes

提供:Dev Guides
移動先:案内検索

例外と例外クラス

一般的に、例外は異常な状態です。 例外は通常エラーを示しますが、プロシージャを早期に終了したり、リソース不足から回復したりする場合など、意図的にプログラムに入れます。 組み込みの例外がいくつかあります。これらの例外は、ファイルの終わりを超えて読み取る、またはゼロで除算するなどの条件を示します。 カスタム例外と呼ばれる独自の例外を定義できます。

例外処理を使用すると、エラーを適切に処理し、意味のあることを実行できます。 例外処理には、「スロー」と「キャッチ」の2つのコンポーネントがあります。

例外の特定(エラー)

Pythonで発生するすべてのエラーは、エラーの種類によって識別されるエラー状態になる例外を発生させます。

>>> #Exception
>>> 1/0
Traceback (most recent call last):
   File "<pyshell#2>", line 1, in <module>
      1/0
ZeroDivisionError: division by zero
>>>
>>> var = 20
>>> print(ver)
Traceback (most recent call last):
   File "<pyshell#5>", line 1, in <module>
      print(ver)
NameError: name 'ver' is not defined
>>> #Above as we have misspelled a variable name so we get an NameError.
>>>
>>> print('hello)

SyntaxError: EOL while scanning string literal
>>> #Above we have not closed the quote in a string, so we get SyntaxError.
>>>
>>> #Below we are asking for a key, that doen't exists.
>>> mydict = {}
>>> mydict['x']
Traceback (most recent call last):
   File "<pyshell#15>", line 1, in <module>
      mydict['x']
KeyError: 'x'
>>> #Above keyError
>>>
>>> #Below asking for a index that didn't exist in a list.
>>> mylist = [1,2,3,4]
>>> mylist[5]
Traceback (most recent call last):
   File "<pyshell#20>", line 1, in <module>
      mylist[5]
IndexError: list index out of range
>>> #Above, index out of range, raised IndexError.

キャッチ/トラッピングの例外

プログラムで異常が発生し、例外メカニズムを使用してそれを処理する場合、「例外をスロー」します。 キーワードtryおよびexceptは、例外をキャッチするために使用されます。 tryブロック内でエラーが発生するたびに、Pythonはそれを処理するために一致する以外のブロックを探します。 ある場合、実行はそこでジャンプします。

構文

try:
   #write some code
   #that might throw some exception
except <ExceptionType>:
   # Exception handler, alert the user

try句内のコードは、ステートメントごとに実行されます。

例外が発生した場合、残りのtryブロックはスキップされ、except句が実行されます。

try:
   some statement here
except:
   exception handling

プログラムでエラー処理メカニズムを使用しない場合に何が起こるかを確認するために、いくつかのコードを書きましょう。

number = int(input('Please enter the number between 1 & 10: '))
print('You have entered number',number)

上記のプログラムは、ユーザーが数字を入力する限り正しく動作しますが、ユーザーが他のデータ型(文字列やリストなど)を入力しようとするとどうなりますか。

Please enter the number between 1 > 10: 'Hi'
Traceback (most recent call last):
   File "C:/Python/Python361/exception2.py", line 1, in <module>
      number = int(input('Please enter the number between 1 & 10: '))
ValueError: invalid literal for int() with base 10: "'Hi'"

現在、ValueErrorは例外タイプです。 上記のコードを例外処理で書き直してみましょう。

import sys

print('Previous code with exception handling')

try:
   number = int(input('Enter number between 1 > 10: '))

except(ValueError):
   print('Error..numbers only')
   sys.exit()

print('You have entered number: ',number)

プログラムを実行し、(数値ではなく)文字列を入力すると、異なる結果が得られることがわかります。

Previous code with exception handling
Enter number between 1 > 10: 'Hi'
Error..numbers only

例外を発生させる

独自のメソッドから例外を発生させるには、次のようなraiseキーワードを使用する必要があります

raise ExceptionClass(‘Some Text Here’)

例を見てみましょう

def enterAge(age):
   if age<0:
      raise ValueError('Only positive integers are allowed')
   if age % 2 ==0:
      print('Entered Age is even')
   else:
      print('Entered Age is odd')

try:
   num = int(input('Enter your age: '))
   enterAge(num)
except ValueError:
   print('Only positive integers are allowed')

プログラムを実行し、正の整数を入力します。

期待される出力

Enter your age: 12
Entered Age is even

しかし、負の数を入力しようとすると、

期待される出力

Enter your age: -2
Only positive integers are allowed

カスタム例外クラスの作成

BaseExceptionクラスまたはBaseExceptionのサブクラスを拡張することにより、カスタム例外クラスを作成できます。

カスタム例外クラス

上記の図から、Pythonのほとんどの例外クラスがBaseExceptionクラスから拡張されていることがわかります。 BaseExceptionクラスまたはそのサブクラスから独自の例外クラスを派生できます。

NegativeNumberException.pyという新しいファイルを作成し、次のコードを記述します。

class NegativeNumberException(RuntimeError):
   def __init__(self, age):
      super().__init__()
      self.age = age

上記のコードは、NegativeNumberExceptionという名前の新しい例外クラスを作成します。これは、super()init()を使用して親クラスコンストラクターを呼び出し、年齢を設定するコンストラクターのみで構成されます。

次に、独自のカスタム例外クラスを作成するために、いくつかのコードを記述し、新しい例外クラスをインポートします。

from NegativeNumberException import NegativeNumberException
def enterage(age):
   if age < 0:
      raise NegativeNumberException('Only positive integers are allowed')

   if age % 2 == 0:
      print('Age is Even')

   else:
      print('Age is Odd')

try:
   num = int(input('Enter your age: '))
   enterage(num)
except NegativeNumberException:
   print('Only positive integers are allowed')
except:
   print('Something is wrong')

出力

Enter your age: -2
Only positive integers are allowed

カスタム例外クラスを作成する別の方法。

class customException(Exception):
   def __init__(self, value):
      self.parameter = value

   def __str__(self):
      return repr(self.parameter)
try:
   raise customException('My Useful Error Message!')
except customException as instance:
   print('Caught: ' + instance.parameter)

出力

Caught: My Useful Error Message!

例外階層

組み込み例外のクラス階層は次のとおりです-

+-- SystemExit
+-- KeyboardInterrupt
+-- GeneratorExit
+-- Exception
+-- StopIteration
+-- StopAsyncIteration
+-- ArithmeticError
| +-- FloatingPointError
| +-- OverflowError
| +-- ZeroDivisionError
+-- AssertionError
+-- AttributeError
+-- BufferError
+-- EOFError
+-- ImportError
+-- LookupError
| +-- IndexError
| +-- KeyError
+-- MemoryError
+-- NameError
| +-- UnboundLocalError
+-- OSError
| +-- BlockingIOError
| +-- ChildProcessError
| +-- ConnectionError
| | +-- BrokenPipeError
| | +-- ConnectionAbortedError
| | +-- ConnectionRefusedError
| | +-- ConnectionResetError
| +-- FileExistsError
| +-- FileNotFoundError
| +-- InterruptedError
| +-- IsADirectoryError
| +-- NotADirectoryError
| +-- PermissionError
| +-- ProcessLookupError
| +-- TimeoutError
+-- ReferenceError
+-- RuntimeError
| +-- NotImplementedError
| +-- RecursionError
+-- SyntaxError
| +-- IndentationError
| +-- TabError
+-- SystemError
+-- TypeError
+-- ValueError
| +-- UnicodeError
| +-- UnicodeDecodeError
| +-- UnicodeEncodeError
| +-- UnicodeTranslateError
+-- Warning
+-- DeprecationWarning
+-- PendingDeprecationWarning
+-- RuntimeWarning
+-- SyntaxWarning
+-- UserWarning
+-- FutureWarning
+-- ImportWarning
+-- UnicodeWarning
+-- BytesWarning
+-- ResourceWarning