2020年5月16日土曜日

Python エラーを克服する

Pythonにはどんなエラーがあるのでしょう?


例外クラスをつくるには
class ParamError(Exception):
 
    pass
 
def sample(num):
    if type(num)!=int:
        raise ParamError('パラメータが不正です')
  
    return num * 10



サンプル デバッグに便利
import traceback try: raise Exception except: with open("error.log", 'a') as f: traceback.print_exc(file=f



class minError(Exception): pass while True: try: x = int(input("Please enter a number: ")) """ if x <0: raise minError("") """ if x <0 or x>100: raise ValueError break except ValueError as e: print("Try again",e) except minError: print("error Try again")


























ちょっと調べてみました



BaseException
 +-- SystemExit
 +-- KeyboardInterrupt
 +-- GeneratorExit
 +-- Exception
      +-- StopIteration
      +-- StopAsyncIteration
      +-- ArithmeticError
      |    +-- FloatingPointError
      |    +-- OverflowError
      |    +-- ZeroDivisionError
      +-- AssertionError
      +-- AttributeError
      +-- BufferError
      +-- EOFError
      +-- ImportError
      |    +-- ModuleNotFoundError
      +-- 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

Python エラー処理

エラー処理は、この形を覚えること!

try:
    処理1
    処理2
    処理3
expect:
    print("エラー発生")
else:
    print("エラーが無かった(よかった)")
finally:

    print("すべての道は、ここに!")